如何捕捉 ctrl-c 事件?
如何在 C++ 中捕获 Ctrl+C 事件?
How do I catch a Ctrl+C event in C++?
推荐答案
signal
不是最可靠的方法,因为它在实现上有所不同.我建议使用 sigaction
.Tom 的代码现在看起来像这样:
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d
",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;
}
相关文章