如果向进程发送信号,则进程中的哪个线程将处理该信号是不确定的。
根据pthread(7) http://linux.die.net/man/7/pthreads:
POSIX.1 还要求线程共享一系列其他属性(即这些属性是进程范围的而不是每个线程的):
...
- 信号处理
...
POSIX.1 区分了定向到整个进程的信号和定向到各个线程的信号的概念。根据 POSIX.1,进程定向信号(使用发送kill(2)
,例如)应该由单个处理,任意地进程内选定的线程。
如果您希望进程中的专用线程来处理某些信号,请参阅以下示例pthread_sigmask(3) http://linux.die.net/man/3/pthread_sigmask向您展示如何操作:
下面的程序阻塞主线程中的一些信号,然后创建一个专用线程通过 sigwait(3) 获取这些信号。以下 shell 会话演示了其用法:
$ ./a.out &
[1] 5423
$ kill -QUIT %1
Signal handling thread got signal 3
$ kill -USR1 %1
Signal handling thread got signal 10
$ kill -TERM %1
[1]+ Terminated ./a.out
节目来源
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
/* Simple error handling functions */
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
static void *
sig_thread(void *arg)
{
sigset_t *set = arg;
int s, sig;
for (;;) {
s = sigwait(set, &sig);
if (s != 0)
handle_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;
/* Block SIGQUIT and SIGUSR1; other threads created by main()
will inherit a copy of the signal mask. */
sigemptyset(&set);
sigaddset(&set, SIGQUIT);
sigaddset(&set, SIGUSR1);
s = pthread_sigmask(SIG_BLOCK, &set, NULL);
if (s != 0)
handle_error_en(s, "pthread_sigmask");
s = pthread_create(&thread, NULL, &sig_thread, (void *) &set);
if (s != 0)
handle_error_en(s, "pthread_create");
/* Main thread carries on to create other threads and/or do
other work */
pause(); /* Dummy pause so we can test program */
}