1. 以下代码取自pthread_sigmask函数的man手册。它实现了在一个线程中统一处理信号。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#define handler_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
static void* sig_thread(void *arg)
{
sigset_t *set = (sigset_t*)arg;
int s, sig;
for (;;) {
//等待信号
s = sigwait(set, &sig);
if (s != 0)
handler_error_en(s, "sigwait");
printf("Signal handling thread got signal %d\n", sig);
}
}
int main(int argc, char *argv[])
{
pthread_t thread;
sigset_t set;
int s;
//在主线程中设置信号掩码
sigemptyset(&set);
sigaddset(&set, SIGQUIT);
sigaddset(&set, SIGUSR1);
s = pthread_sigmask(SIG_BLOCK, &set, NULL);
if (s != 0)
handler_error_en(s, "pthread_sigmask");
s = pthread_create(&thread, NULL, &sig_thread, (void*)&set);
if (s != 0)
handler_error_en(s, "pthread_create");
pause();
return 0;
}