使用sigwait同步处理异步信号

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>


sigset_t mask;


void* thr_func(void* arg)
{
int err;
int signo;
pthread_t tid = pthread_self();
pthread_detach(tid);


while(1)
{
err = sigwait(&mask,&signo);
if( err != 0){
fprintf(stderr,"sigwait err=%d\n",err);
exit(-1);
}
switch(signo){
case SIGINT:
printf("receive SIGINT in thr_func\n");
break;
case SIGQUIT:
printf("receive SIGQUIT in thr_func\n");
break;
default:
printf("receive other signo = %d\n",signo);
break;
}
}


}


void* workthr_func(void* arg)
{
pthread_t tid = pthread_self();
pthread_detach(tid);
fprintf(stdout,"this is the work thread 1\n");
//printf("getpid()=%d\n",getpid());
kill(getpid(),SIGQUIT);
    printf("send SIGQUIT from workthr 1\n");
sleep(1);
exit(0);
}


void* workthr_func2(void* arg)
{
pthread_t tid = pthread_self();
pthread_detach(tid);
fprintf(stdout,"this is the work thread 2\n");


//printf("getpid()=%d\n",getpid());
kill(getpid(),SIGINT);
printf("send SIGINT from workthr 2\n");
sleep(1);
exit(0);
}


int main(void)
{
sigset_t old;
pthread_t tid;
pthread_t tid2;
pthread_t tid3;
pid_t pid = getpid();
int err;
sigemptyset(&mask);
sigaddset(&mask,SIGINT);
sigaddset(&mask,SIGQUIT);



//printf("main thread pid = %d\n",getpid());


if( (err=pthread_sigmask(SIG_BLOCK,&mask,&old)) != 0 ){
fprintf(stdout,"pthread_sigmask err=%d \n",err);
exit(-1);
}

err = pthread_create(&tid,NULL,thr_func,0);
if(err != 0){
fprintf(stdout,"signal thread create error\n");
exit(-1);
}






err = pthread_create(&tid2,NULL,workthr_func,0);
if(err != 0){
fprintf(stdout,"work thread create error\n");
exit(-1);
}

err = pthread_create(&tid3,NULL,workthr_func2,0);
if(err != 0){
printf("create thread2 error\n");
exit(-1);
}





kill(pid,SIGINT);
kill(pid,SIGQUIT);
 // kill(pid,SIGUSR1);
 // kill(pid,SIGUSR2);


sleep(3);
exit(0);

}


程序首先屏蔽SIGINT和SIGQUIT,然后创建信号处理线程,之后再继续创建两个工作线程,工作线程给信号处理线程分别发送信号,主线程最后也给自己发送信号。如果最后的kill(pid,SIGUSR1);不屏蔽,那么程序会终止并且只显示接受一个信号,我的理解是sigusr1默认处理就是退出程序,但是为何之前发送的信号不能够被处理不太清楚。而且程序加入发送多个SIGINT那么最后就会只收到一个,这个也不太清楚。以后补充!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值