Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ctrl-c的信号处理程序-需要无限循环的帮助吗_C_Linux_Signals_Signal Handling - Fatal编程技术网

使用ctrl-c的信号处理程序-需要无限循环的帮助吗

使用ctrl-c的信号处理程序-需要无限循环的帮助吗,c,linux,signals,signal-handling,C,Linux,Signals,Signal Handling,我正在使用ctrl-c信号的信号处理程序。i、 e每当生成ctrl-c信号而不是退出应用程序时,我都会执行一些操作 让我们假设,如果我的应用程序由于while(1)循环(任何错误条件)而挂起,我是否可以仅在这种情况下退出应用程序 例: 谢谢在收到类似于Ctrl-C的信号之前,很难确定代码是否处于意外的无限循环中。我可以建议一些启发式方法。有一个足够长的变量,最好是一个全局的无符号long long int,并在循环中不断增加这个变量,你怀疑它可能在循环的每次迭代中滑入无限循环。现在,当您收到一个

我正在使用ctrl-c信号的信号处理程序。i、 e每当生成ctrl-c信号而不是退出应用程序时,我都会执行一些操作

让我们假设,如果我的应用程序由于while(1)循环(任何错误条件)而挂起,我是否可以仅在这种情况下退出应用程序

例:


谢谢

在收到类似于
Ctrl-C
的信号之前,很难确定代码是否处于意外的无限循环中。我可以建议一些启发式方法。有一个足够长的变量,最好是一个全局的
无符号long long int
,并在循环中不断增加这个变量,你怀疑它可能在循环的每次迭代中滑入无限循环。现在,当您收到一个信号时,根据阈值
MAX\u NUMBER\u of \u ITERATIONS
检查信号处理程序中该变量的值。如果变量超过用户定义的阈值,则声明一个无限循环,然后退出,否则继续

这句话的意思是什么-

或者更简单的是,只要使用
SIG\u IGN
忽略
SIGINT
,并
中断故障循环,一旦检测到故障,打印出错误消息并退出

1)您的信号处理程序的声明/定义/签名错误,应该是
void handle(int signum)2:lookup
man 2 siglongjmp
2)siglongjmp 3)将条件变量声明为“volatile”,以避免编译器缓存其值。
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);
}
#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;
   }

}