【发布时间】:2011-09-02 18:22:51
【问题描述】:
以下代码仅捕获一次“SIGINT”信号然后中断(程序存在):
#include <signal.h>
#include <stdio.h>
void IntHandler(int value);
void CatchIntSignal()
{
struct sigaction intAction;
intAction.sa_handler = IntHandler;
sigemptyset(&intAction.sa_mask);
intAction.sa_flags = 0;
//if to uncomment any of "0" or "SIG_IGN" - IntHandler will be never called:
//intAction.sa_sigaction = 0/*SIG_IGN*/;
if(sigaction(SIGINT, &intAction, NULL) != 0)
{
printf("sigaction() failed.\n");
}
}
void IntHandler(int value)
{
printf("IntHandler(%d)\n", value);
//uncommenting this does not help:
//CatchIntSignal();
}
int main()
{
CatchIntSignal();
getchar();
return 0;
}
我必须如何修改此代码以在 SIGINT 捕获后保留程序的退出? 如果将 intAction.sa_sigaction 设置为 0 或 SIG_IGN - IntHandler 将永远不会被调用 - 但为什么呢?哪个未定义的值必须说系统“有必要调用 IntHandler”?如果我将一些处理程序设置为 intAction.sa_sigaction - 这个处理程序将被调用(但 IntHandler 不会)。系统如何知道我确实为 intAction.sa_sigaction 设置了一些东西?
【问题讨论】:
-
我不明白你想让你的程序做什么。是不是:第一次收到SIGINT,调用IntHandler,然后程序退出?或者是:每次收到SIGINT,都会调用IntHandler;在 getchar() 返回之前程序不会退出?
-
我希望我的程序能够捕获 SIGINT 信号并且不会在它之后退出。这样在每个“Ctrl+C”程序之后都会打印“IntHandler(2)”并继续工作。