虽然没有收到信号?

gEd*_*ger 5 c linux posix signals pthreads

所以我最近一直在用C编程并研究Signals和POSIX线程.我知道我可以在一个线程中等待一个信号,但我一直想知道是否有可能有一个包含一个while循环的线程,该循环将在未收到SIGINT时继续执行.所以基本上我不是在等待信号(停止执行while循环),而是继续执行直到收到信号.只是听一定的信号.

我试过谷歌搜索但无济于事.

有什么建议?提前致谢!!

xbu*_*bug 4

只使用一个简单的信号处理程序怎么样?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

static void sigint_handler( int signum );
volatile static int done = 0;

int main( int argc, char *argv[] )
{
   if( signal( SIGINT, sigint_handler ) == SIG_ERR ) {
      perror( "signal()" );
      exit(1);
   }

   while( !done ) {
      (void)printf( "working...\n" );
      (void)sleep( 1 );
   }

   (void)printf( "got SIGINT\n" );

   return 0;
}

void sigint_handler( int signum )
{ done = 1; }
Run Code Online (Sandbox Code Playgroud)

编辑:变得done不稳定,感谢 Joseph Quinsey 在评论中指出了这一点。请参阅此问题以获取相关讨论,还有这篇文章

  • 注册信号处理程序可能会失败。需要根据“SIG_ERR”检查返回值“signal(SIGINT, sigint_handler)” (4认同)