多线程间信号处理

 
#include "stdio.h" #include "pthread.h" #include "stdlib.h" #include "string.h" #include "unistd.h" #include "signal.h" void sig_handler2(int arg){//线程2信号处理函数 printf("thread2 get signal\n"); return; } void sig_handler1(int arg){ //线程1信号处理函数 printf("thread1 get signa1\n"); return; } void * thread_fun1(void *arg){ printf("new thread 1\n"); struct sigaction act; memset(&act,0,sizeof(act));//清空 sigaddset(&act.sa_mask,SIGQUIT);//添加信号屏蔽字 act.sa_handler=sig_handler1;//指定信号集处理程序
 // 当此次线程接收到信号SIGQUIT时 ,执行act处理函数 sigaction(SIGQUIT,&act,NULL);//为SIGQUIT 信号设置处理函数act,处理函数通过结构体sigaction指定        //设置信号屏蔽,当接受到act中指定的信号进行屏蔽设置 pthread_sigmask(SIG_BLOCK,&act.sa_mask,NULL);//SIG_BLOCK:向当前信号掩码中添加act,其中act表示要阻塞的信号组 //SIG_UNBLOCK:删除信号组 SIG_SETMASK:替换信号组, sleep(2); return (void*)0; } void * thread_fun2(void *arg){ printf("new thread 2\n"); struct sigaction act; memset(&act,0,sizeof(act)); sigaddset(&act.sa_mask,SIGQUIT); act.sa_handler=sig_handler2; sigaction(SIGQUIT,&act,NULL); //pthread_sigmask(SIG_BLOCK,&act.sa_mask,NULL); sleep(2); return (void *)0; } int main(){ pthread_t tid1,tid2; int err; int s; err=pthread_create(&tid1,NULL,thread_fun1,NULL);//创建线程1 if(err!=0){ printf("create new thread 1 failed\n"); return -1; } err=pthread_create(&tid2,NULL,thread_fun2,NULL); //创建线程2 if(err!=0){ printf("create new thread 2 failed\n"); return -1; } sleep(1); s=pthread_kill(tid1,SIGQUIT);//给tid1线程发送信号SIGQUIT if(s!=0){ printf("send signal to thread1 failed\n"); } s=pthread_kill(tid2,SIGQUIT);//给tid1线程发送信号SIGQUIT if(s!=0){ printf("send signal to thread2 failed\n"); } pthread_join(tid1,NULL);//等待tid1线程终止回收 pthread_join(tid2,NULL);//等待tid2线程终止回收 return 0; }

 设置线程信号处理:sigaction(SIGQUIT,&act,NULL);//因为所有线程都以后执行的sigaction为准,结果如下,线程1先执行,所以线程1线程处理函数得到执行。
运行结果:
new thread 2
new thread 1
thread1 get signal1




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值