在这一节中,有几点比较难以理解
int pthead_sigmask
第一点:如果信号集中的某个信号在sigwait调用的时候是挂起状态
这里的挂起是什么意思
应该是所有的线程的将该信号阻塞,并且在调用sigwait 时该信号已经发生,但还没能传递
第二点:线程在调用sigwait 之前,必须阻塞那些它在等待的信号,sigwait函数会原子地取消信号集的阻塞状态。在返回之前,sigwait将恢复线程的信号屏蔽字(
绿色这部分是sigwait的动作)
为了理解这个函数,我们首先要理解它要实现的功能(专用于线程)
将对信号的异步处理,转换成同步处理,也就是说用一个线程专门的来“同步等待”信号的到来,而其它的线程可以完全不被该信号中断/打断(interrupt)。
(这里其他的线程之所以不会被打断是因为它们把这些信号屏蔽了)
下面这个程序将有助于我们理解sigwait函数的作用
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
/* Simpleerror 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=(sigset_t*) 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 SIGINT; 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/ordo
other work
*/
pause();/* Dummy pause so we can test program*/
return 0;
}
输出结果
[root@localhost apue]# gcc -l pthread 10.c[root@localhost apue]# ./a.out &
[1] 17952
[root@localhost apue]# kill -QUIT %1
Signal handling thread got signal 3
[root@localhost apue]# kill -USR1 %1
Signal handling thread got signal 10