在收到类似Ctrl-C
. 我可以建议一些启发式方法。有一个足够长的变量,最好是一个 global unsigned long long int
,并在你怀疑在循环的每次迭代中可能滑入无限循环的循环内不断增加这个变量。现在,当您收到信号时,请根据阈值检查信号处理程序中此变量的值MAX_NUMBER_OF_ITERATIONS
。如果变量超过用户定义的阈值,则声明一个无限循环,exit
否则继续。
这些线上的东西-
#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;
}
}
或者更简单的是,只要检测到故障情况,就忽略SIGINT
使用SIG_IGN
和break
退出故障循环,打印出错误信息并退出!