进程中的信号是递送到单个线程的。如果信号与硬件故障或计时器超时相关,该信号就被发送到引起该事件的线程中去,而其他的信号则被发送到任意一个线程。
为了处理简单,可将信号指定某个线程进行处理。
示意代码:
#include <stdio.h>
#include <signal.h>
int g_exit = 0;
void *thread_signal(void *arg)
{
printf("thread signal start\n");
while (!g_exit)
{
//do anything
sleep(1);
}
}
void *thread_other(void *arg)
{
printf("thread_other start\n");
while (!g_exit)
{
//do anything
sleep(1);
}
}
void signal_handler(int signo)
{
printf("recv signal,thread=%u\n", pthread_self());
g_exit = 1;
}
#define SIGMASK(HOW)\
{\
sigset_t sigset;\
sigemptyset(&sigset);\
sigaddset(&sigset, SIGINT);\
sigaddset(&sigset, SIGQUIT);\
sigaddset(&sigset, SIGHUP);\
sigaddset(&sigset, SIGTERM);\
pthread_sigmask(HOW, &sigset, NULL);\
}while (0);
int main()
{
signal(SIGINT, signal_handler);
signal(SIGQUIT, signal_handler);
signal(SIGHUP, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGPIPE, SIG_IGN);
SIGMASK(SIG_UNBLOCK);
int ret = 0;
pthread_t tid1,tid2,tid3;
ret = pthread_create(&tid1, NULL, thread_signal, NULL);
if (ret != 0)
return -1;
SIGMASK(SIG_BLOCK);
ret = pthread_create(&tid2, NULL, thread_other, NULL);
if (ret != 0)
return -1;
ret = pthread_create(&tid3, NULL, thread_other, NULL);
if (ret != 0)
return -1;
printf("parent thread=%u, tid1=%u, tid2=%u, tid3=%u\n", pthread_self(), tid1, tid2, tid3);
while (!g_exit)
{
//do anything
sleep(1);
}
return 0;
}