如何捕捉 ctrl-c 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1641182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:43:17  来源:igfitidea点击:

How can I catch a ctrl-c event?

c++event-handlingposixsignalssigint

提问by Scott

How do I catch a Ctrl+Cevent in C++?

如何在 C++ 中捕获Ctrl+C事件?

回答by Gab Royer

signalisn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

signal不是最可靠的方法,因为它在实现上有所不同。我会推荐使用sigaction. Tom 的代码现在看起来像这样:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}

回答by Chris Smith

For a Windows console app, you want to use SetConsoleCtrlHandlerto handle CTRL+Cand CTRL+BREAK.

对于 Windows 控制台应用程序,您希望使用SetConsoleCtrlHandler来处理CTRL+CCTRL+ BREAK

See herefor an example.

有关示例,请参见此处

回答by Tom

You have to catch the SIGINT signal(we are talking POSIX right?)

您必须捕捉 SIGINT信号(我们说的是 POSIX,对吗?)

See @Gab Royer′s answer for sigaction.

请参阅@Gab Royer 对 sigaction 的回答。

Example:

例子:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

回答by Joyer

Yeah, this is a platform dependent question.

是的,这是一个平台相关的问题。

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

如果您正在 POSIX 上编写控制台程序,请使用信号 API ( #include <signal.h>)。

In a WIN32 GUI application you should handle the WM_KEYDOWNmessage.

在 WIN32 GUI 应用程序中,您应该处理该WM_KEYDOWN消息。