我正在使用 ctrl-c 信号的信号处理程序。即每当生成 ctrl-c 信号而不是退出应用程序时,我都会执行一些操作。
让我们假设,如果我的应用程序由于 while(1) 循环(任何错误条件)而挂起,我是否可以仅在这种情况下退出应用程序?
例如:
void handle()
{
/*do some action*/
----
----
---
if ( while(1) detected)
{
exit(0);
}
}
main()
{
struct sigaction myhandle;
myhandle.sa_handler = handle;
sigemptyset(&myhandle.sa_mask);
myhandle.sa_flags = 0;
sigaction(SIGINT, &myhandle, NULL);
while(1);
}
谢谢
最佳答案
在收到 Ctrl-C
等信号之前,很难确定您的代码是否处于意外的无限循环中。我可以建议一些启发式方法。拥有一个足够长的变量,最好是全局 unsigned long long int
,并在循环内不断递增该变量,您怀疑循环的每次迭代可能会陷入无限循环。现在,当您收到信号时,请根据阈值 MAX_NUMBER_OF_ITERATIONS
检查信号处理程序中此变量的值。如果变量超过用户定义的阈值,则声明无限循环并退出
,否则只需继续。
关于这些的东西-
#define MAX_NUMBER_OF_ITERATIONS 100000000
unsigned long long checkForEndlessLoop=0;
bool overflow;
void sigHandler (int signum)
{
signal(sig, SIG_IGN); // Ignore it so that another Ctrl-C doesn't appear any soon
if (overflow || (checkForEndlessLoop > MAX_NUMBER_OF_ITERATIONS) )
{
//Something's fishy in the loop.
exit(0);
}
else
{
signal(SIGINT, sigHandler );
}
}
int main ()
{
signal(SIGINT, sigHandler );
for (checkForEndlessLoop=0; SOME_SLOPPY_CONDITION; )
{
//Some processing here
if (++checkForEndlessLoop == 0 )
overflow=true;
}
checkForEndlessLoop=0;
while (SOME_SLOPPY_CONDITION)
{
//Some processing here
if (++checkForEndlessLoop == 0 )
overflow=true;
}
}
或者更简单的是,只需使用 SIG_IGN
忽略 SIGINT
并在检测到错误情况后立即 break
跳出错误循环,打印出错误信息并退出!
关于c - 使用 ctrl-c 的信号处理程序 - 需要无限循环的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10242843/