- 概念
- pthread_sigmask
- pthread_kill 和 sigwait
概念
- 按照 POSIX, 异步 (外部) 信号发送到整个进程.
- 所有线程共享同一个设置, 即通过 sigaction 设置的线程处置方法.
- 每个线程有自己的信号掩码, 线程库根据该掩码决定将信号发送到哪个线程.
- 由于 Linux 线程实现上的独特性, 外部信号始终发送到特定的线程.
pthread_sigmask
- pthread_sigmask 用来定义线程的信号掩码
- 其接口与 sigprocmask 一样
===============================================================================
#include
#include
int pthread_sigmask (int how, const sigset_t *newmask, sigset_t *oldmask);
===============================================================================
pthread_kill 和 sigwait
===============================================================================
#include
#include
int pthread_kill (pthread_t thread, int signo);
int sigwait (const sigset_t *set, int *sig);
===============================================================================
- pthread_kill 向特定的线程发送信号.
- sigwait 暂定调用线程, 直到 set 中定义的某个信号递达调用线程.
- sigwait 返回时, sig 中保存的是接收到的信号编号.
- sigwait 所等待的信号必须在所有线程中阻塞, 而不仅仅是调用线程.
#include
#include
#include
#include
#include
#include
//进程接收到信号后阻塞,线程处理完毕后再通知进程
sigset_t set;
int quitflag = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void * thr_fn(void * arg)
{
int err,signo;
for(;;)
{
sigwait(&set,&signo);
switch(signo)
{
case SIGUSR2:
printf("thread 1 recieve sigusr2.\n");
break;
case SIGUSR1:
pthread_mutex_lock(&lock);
quitflag=1;
pthread_cond_signal(&wait);
printf("thread 1 recieve sigusr1\n");
pthread_mutex_unlock(&lock);
pthread_exit((void *)0);
default:
printf("thread 1 recieve unexpected signal %d\n",signo);
pthread_exit((void *)1);
}
}
pthread_exit((void *)0);
}
int main(int argc,char ** argv)
{
sigset_t oldset;
pthread_t tid;
int err;
sigemptyset(&set);
sigemptyset(&oldset);
sigaddset(&set,SIGUSR1);
sigaddset(&set,SIGUSR2);
pthread_sigmask(SIG_BLOCK,&set,&oldset);
pthread_create(&tid,NULL,thr_fn,NULL);
sleep(2);
kill(getpid(),SIGUSR2);
kill(getpid(),SIGUSR1);
pthread_mutex_lock(&lock);
while(quitflag==0)
pthread_cond_wait(&wait,&lock);
pthread_mutex_unlock(&lock);
printf("main eixt.\n");
quitflag=0;
sigprocmask(SIG_SETMASK,&oldset,NULL);
printf("recover sigmask.\n");
pthread_join(tid,NULL);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&wait);
return 0;
}
阅读(481) | 评论(0) | 转发(0) |