虽然没有收到信号?

时间:2014-12-02 23:29:57

标签: c linux pthreads signals posix

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

我尝试使用谷歌搜索,但无济于事。

有什么建议吗?在此先感谢!!

2 个答案:

答案 0 :(得分:3)

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

#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; }

编辑:由于Joseph Quinsey在评论中指出了这一点,因此done不稳定。有关相关讨论,请参阅this questionthis article

答案 1 :(得分:2)

您可以阻止信号,然后使用sigtimedwait()以零超时来轮询它。

在主线程中,在创建任何其他线程之前,阻止SIGINT。随后创建的线程将继承信号掩码,因此SIGINT将在所有线程中被阻止:

sigset_t sigint_set;

sigemptyset(&sigint_set);
sigaddset(&sigint_set, SIGINT);    
sigprocmask(SIG_BLOCK, &sigint_set, NULL);

然后在你要循环查询SIGINT的线程中:

sigset_t sigint_set;
siginfo_t info;
const struct timespec zero_timeout = { 0, 0 };

sigemptyset(&sigint_set);
sigaddset(&sigint_set, SIGINT);    

while (sigtimedwait(&sigint_set, &info, &zero_timeout) != SIGINT)
{
    /* Do something */
}