歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux C語言:開啟一個專門用來接收信號的子線程

Linux C語言:開啟一個專門用來接收信號的子線程

日期:2017/3/1 10:03:16   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved