C ++控制台打破 [英] C++ Console Breaking

查看:168
本文介绍了C ++控制台打破的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道什么是最好的方法触发一个函数(所以我可以执行一个优雅的退出)在C + +控制台应用程序在Ctrl + C是?

Wondering what the best way to trigger a function ( so I can perform a graceful exit ) in a C++ console application on Ctrl+C is?

推荐答案

标准C方式:

#include <signal.h>

void interrupted(int sig) {
    /* do something ... */
    exit(0);
}

int main(void) {
    signal(SIGINT, interrupted);

    /* now the problem can start up ....  */
}


b $ b

通常,您还需要连接SIGTERM,这是在关闭程序的请求时发送的。但上面足够处理Ctrl + C

Usually you also want to connect SIGTERM, which is sent when a request to close the program is made. But the above suffices to handle Ctrl+C

你应该注意不要在处理程序中做一些耗时的事情。有一个竞争条件:处理程序是否设置为默认值在系统之间是不同的。因此,如果在你的处理程序中用户再次中断程序,它将中断你的处理程序并退出。更好地使用 sigaction (这不是标准C),没有这个问题。

You should take care not to do something time consuming in the handler. There is a race-condition: Whether or not the handler is set back to default is different among systems. Thus, if in your handler the user interrupts the program again, it will interrupt your handler and exit. Better to use sigaction (that is however not Standard C), which doesn't have this problem.

这篇关于C ++控制台打破的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆