按“Ctrl+C"时如何防止控制台应用程序终止在 C? [英] How to prevent Console Application from terminating when pressing "Ctrl+C" in C?
本文介绍了按“Ctrl+C"时如何防止控制台应用程序终止在 C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现在 Windows 上从 GCC 编译的控制台应用程序总是在按下 Ctrl+C 时终止.
I found that Console Application compiled from GCC on Windows always terminate when pressing Ctrl+C.
在按下Ctrl+C时,是否有任何可行的方法可以防止控制台应用程序终止?
Is there any feasible way to prevent Console Application from terminating when pressing Ctrl+C?
推荐答案
当用户按下控件 C 时,一个信号 (SIGINT) 被发送到您的进程.当大多数信号发送到一个进程时,该进程必须要么处理该信号,要么操作系统将杀死它.所以...你需要做的就是为 SIGINT 安装一个信号处理程序.
When the user presses control C, a signal (SIGINT) is sent to your process. When most signals are sent to a process, that process must either handle the signal or the operating system will kill it. So... all you need to do is install a signal handler for SIGINT.
以下内容未经测试:
#include <signal.h>
static void ignore_control_c(int sig)
{
/* re-arm the signal handler but otherwise ignore the signal */
signal(sig, ignore_control_c);
}
int main(int argc, char *argv)
{
signal(SIGINT, ignore_control_c);
...
这篇关于按“Ctrl+C"时如何防止控制台应用程序终止在 C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文