Windows控制台应用程序-结束事件的信号 [英] Windows console application - signal for closing event
问题描述
在Windows控制台应用程序中,可以使用以下命令捕获 ctrl + c
:
In windows console application, one can catch pressing ctrl+c
by using:
#include <stdio.h>
#include <signal.h>
void SigInt_Handler(int n_signal)
{
printf("interrupted\n");
}
int main(int n_arg_num, const char **p_arg_list)
{
signal(SIGINT, &SigInt_Handler);
getchar(); // wait for user intervention
}
此方法很好用,但不适用于如果用户按下十字×
关闭控制台窗口,则全部显示。有信号吗?
This works well, except it does not work at all if the user presses the cross ×
that closes the console window. Is there any signal for that?
我需要这个的原因是我有这个CUDA应用程序,如果在计算内容时关闭它,它往往会使计算机崩溃。该代码是多平台的,因此我更喜欢使用信号,而不是 SetConsoleCtrlHandler
。有办法吗?
The reason I need this is I have this CUDA application which tends to crash the computer if closed while computing something. The code is kind of multiplatform so I'd prefer using signals rather than SetConsoleCtrlHandler
. Is there a way?
推荐答案
正确的方法是 SIGBREAK
,您可以尝试以下操作:
The correct one is SIGBREAK
, you can try it with:
#include <stdio.h>
#include <signal.h>
void SigInt_Handler(int n_signal)
{
printf("interrupted\n");
exit(1);
}
void SigBreak_Handler(int n_signal)
{
printf("closed\n");
exit(2);
}
int main(int n_arg_num, const char **p_arg_list)
{
signal(SIGINT, &SigInt_Handler);
signal(SIGBREAK, &SigBreak_Handler);
getchar(); // wait for user intervention
return 0;
}
关闭控制台窗口后,程序将打印 已关闭
,并将返回2。
Upon closing the console window, the program will print "closed"
and will return 2.
这篇关于Windows控制台应用程序-结束事件的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!