0

我正在为 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);
}

谢谢

4

1 回答 1

0

在收到类似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_IGNbreak退出故障循环,打印出错误信息并退出!

于 2012-04-20T09:40:43.723 回答