receive user1 signal 1 times
send SIGUSR1
receive user1 signal 2 times
send SIGUSR1
receive user1 signal 3 times
send SIGUSR1
receive user1 signal 4 times
send SIGUSR1
receive user1 signal 5 times
send SIGUSR1
sleep started
sleep finished
#include <stdio.h>#include <signal.h>#include <stdlib.h>staticvoidsigusr1_handler(intsigno);intmain(){sigset_toldmask,newmask,pendmask;//加入SIGUSR1信号处理函数if(signal(SIGUSR1,sigusr1_handler)==SIG_ERR){printf("signal error\n");exit(1);}//阻止SIGUSR1信号sigemptyset(&newmask);sigaddset(&newmask,SIGUSR1);if(sigprocmask(SIG_BLOCK,&newmask,&oldmask)<0){printf("sigprocmask block error\n");exit(1);}printf("SIGUSR1 is blocked\n");//发出信号inti;for(i=0;i<5;i++){raise(SIGUSR1);printf("send SIGUSR1\n");}printf("sleep started\n");sleep(5);printf("sleep finished\n");if(sigpending(&pendmask)<0){printf("sigpending error\n");exit(1);}if(sigismember(&pendmask,SIGUSR1)){printf("SIGUSR1 was pending\n");}//恢复之前的信号掩码if(sigprocmask(SIG_SETMASK,&oldmask,NULL)<0){printf("sigprocmask setmask error\n");exit(1);}printf("restore old signal mask\n");exit(0);}staticvoidsigusr1_handler(intsigno){staticintn=1;printf("receive user1 signal %d times\n",n++);if(signal(SIGUSR1,sigusr1_handler)==SIG_ERR){printf("can't reset SIGUSR1");exit(1);}}
再来看运行的结果:
SIGUSR1 is blocked
send SIGUSR1
send SIGUSR1
send SIGUSR1
send SIGUSR1
send SIGUSR1
sleep started
sleep finished
SIGUSR1 was pending
receive user1 signal 1 times
restore old signal mask