Linux C语言:开启一个专门用来接收信号的子线程


Linux C语言:开启一个专门用来接收信号的子线程。

以下这个小程序实现这个功能。

上代码:

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

//程序发生了严重的错误,输出
void error_quit(const char *str)
{
 fprintf(stderr, "%s\n", str);
 exit(1);
}

//专门用于接收信号的线程函数
static void *sig_thread(void *arg)
{
 printf("subthread tid: %u\n", (unsigned int)pthread_self());
 sigset_t *set = (sigset_t *) arg;
 int res, sig;

 while( 1 )
 {
  //挂起程序,等待信号的到来
  res = sigwait(set, &sig);
  if( res != 0 )
   error_quit("sigwait error");
  printf("tid: %u  ", (unsigned int)pthread_self());
 
  if( SIGALRM == sig )
  {
   printf("time out\n");
   //循环设置闹钟信号,每5秒响一次
   alarm(5);
  }
  else if( SIGTSTP == sig )
  {
   printf("catch quit signal\n");
   break;
  }
  else if( SIGINT == sig )
  {
   printf("quit program\n");
   exit(0);
  }
 }
}

int main(int argc, char *argv[])
{
 pthread_t stid;
 sigset_t set;
 int res;
 printf("main pid: %u, tid: %u\n",
  (unsigned int)getpid(),
  (unsigned int)pthread_self());

 //设置要被线程处理的信号集
 sigemptyset(&set);
 sigaddset(&set, SIGINT);
 sigaddset(&set, SIGTSTP);
 sigaddset(&set, SIGALRM);
 res = pthread_sigmask(SIG_BLOCK, &set, NULL);
 if( res != 0 )
  error_quit("pthread sigmask error");

 alarm(1);
 //开启信号处理线程,并让主线程等待其退出后才退出
 res = pthread_create(&stid, NULL, &sig_thread, (void *) &set);
 if (res != 0)
  error_quit("pthread_create error");
 pthread_join(stid, NULL);
 printf("finish\n");

 return 0;
}

相关内容