我有2个线程(线程1和线程)。我有SIGINT
信号配置。每当SIGINT
发生线程2应该处理的信号。对于我写了下面的程序
void sig_hand(int no) //signal handler
{
printf("handler executing...\n");
getchar();
}
void* thread1(void *arg1) //thread1
{
while(1) {
printf("thread1 active\n");
sleep(1);
}
}
void * thread2(void * arg2) //thread2
{
signal(2, sig_hand);
while(1) {
printf("thread2 active\n");
sleep(3);
}
}
int main()
{
pthread_t t1;
pthread_t t1;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
while(1);
}
我编译和运行程序。对于每1秒“线程1活性”是打印和用于每3秒“线程2活性”正在打印。
现在我产生SIGINT
。但其印刷“线程1活动”和“线程2活跃”像上述消息。再次我生成SIGINT
,现在为每3秒只有“线程2活性”消息是打印。我再次产生SIGINT
,现在所有线程被阻塞。
所以我的理解,用于执行信号处理程序第一次主线程。对于第二次执行线程1处理程序,并最后线程2执行信号处理程序。
我怎么能写,只要发生信号一样的代码,只有线程2必须执行我的信号处理程序?
如果发送信号的过程,其中螺纹的过程中会处理这个信号是不确定的。
POSIX.1还要求线程共享的范围内的其他属性的(即,这些属性是进程范围,而不是每个线程): ... - 信号处置 ...
POSIX.1区分的被引导到过程作为一个整体,信号被引导到各个线程的信号的概念。根据POSIX.1,处理向信号(使用
kill(2)
发送,例如)应该由进程内的单个,任意选择的线程来处理。
如果你想有一个专门的线程在你的进程来处理一些信号,这里是一个pthread_sigmask(3)
例子展示了如何做到这一点:
下面的块的方案的一些信号在主线程,然后创建专用线程通过调用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 */
}
请仔细阅读signal(7)&pthread(7)&pthread_kill(3)&sigprocmask(2)&pthread_sigmask(3)哪位可以使用(以阻止不需要的线程SIGINT
)。还阅读了pthread tutorial。
避免使用信号进行通信或线程之间的同步。例如考虑互斥(pthread_mutex_lock等)和条件变量(pthread_cond_wait等)。
如果一个线程运行的event loop(例如,大约poll(2) ...)考虑使用signalfd(2)。