- 信号传递的时机
1.进程被再度调度时。
意味着获得执行时间片。
2.系统调用完成时。
信号的传递可能引起阻塞的系统调用过早完
- 解除信号阻塞时,信号的传递顺序
linux 内核时按照信号编号的升序来传递信号的。
测试一下
1 #include <signal.h> 2 #include <string.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 static void sig_int(int signo) { 7 if (signo == SIGINT) 8 printf("SIGINT interrupt ,%d\n", SIGINT); 9 else if ( signo == SIGQUIT) 10 printf("SIGQUIT interrupt %d\n", SIGQUIT); 11 12 } 13 14 int main(int argc, char const *argv[]) 15 { 16 17 sigset_t pendmask, oldmask, zeromask; 18 signal(SIGINT, sig_int); 19 signal(SIGQUIT, sig_int); 20 sigfillset(&pendmask); 21 printf("block all \n"); 22 sigprocmask(SIG_BLOCK, &pendmask, &oldmask); 23 raise(SIGQUIT); 24 raise(SIGINT); 25 sleep(2); 26 printf("unblock \n"); 27 sigprocmask(SIG_SETMASK, &oldmask, &oldmask); 28 printf("exit\n"); 29 30 return 0; 31 }
执行结果
block all
unblock
SIGQUIT interrupt 3
SIGINT interrupt ,2
exit
为什么 SIGQUIT(3)先被执行,难道有问题?
看看下面的测试程序
1 #include <signal.h> 2 #include <string.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 static void sig_int(int signo) { 7 if (signo == SIGINT) 8 printf("SIGINT interrupt ,%d\n", SIGINT); 9 else if ( signo == SIGQUIT) 10 printf("SIGQUIT interrupt %d\n", SIGQUIT); 11 else if ( signo == SIGTERM) 12 printf("SIGTERM interrupt %d\n", SIGTERM); 13 } 14 15 int main(int argc, char const *argv[]) 16 { 17 18 sigset_t pendmask, oldmask, zeromask; 19 struct sigaction sa; 20 sigfillset(&pendmask); 21 sa.sa_flags = 0; 22 sa.sa_handler = sig_int; 23 sa.sa_mask = pendmask; 24 sigaction(SIGINT, &sa, NULL); 25 sigaction(SIGQUIT, &sa, NULL); 26 sigaction(SIGTERM, &sa, NULL); 27 sigaction(SIGUSR1, &sa, NULL); 28 printf("block all \n"); 29 sigprocmask(SIG_BLOCK, &pendmask, &oldmask); 30 raise(SIGUSR1); 31 raise(SIGQUIT); 32 raise(SIGINT); 33 raise(SIGTERM); 34 sleep(2); 35 printf("unblock \n"); 36 sigprocmask(SIG_SETMASK, &oldmask, &oldmask); 37 printf("exit\n"); 38 39 return 0; 40 }
执行结果
block all
unblock
SIGINT interrupt ,2
SIGQUIT interrupt 3
SIGTERM interrupt 15
exit
原来是信号处理程序时没有屏蔽信号,导致的。