Linux可靠/不可靠信号编程实践
综合案例
1) 创建子进程与父进程;
2) 注册SIGINT非实时信号与SIGRTMIN实时信号,并将这两种信号添加到进程屏蔽信号组中;
3) 注册用户自定义信号;
4) 子进程发送5次非实时信号,发5次实时信号;
5) 然后子进程发送SIGUSR1解除进程对SIGINT,SIGTRMIN信号的阻塞
6) 观察实时信号与非实时信号的区别
//程序示例 void onSigAction(int signalNumber, siginfo_t *sigInfoStruct, void *) { //获取接收到的数据 int receiveNumber = sigInfoStruct->si_int; //如果收到的是SIGUSR1信号,则解除对SIGINT,SIGRTMIN的屏蔽 if (signalNumber == SIGUSR1) { sigset_t unblockSet; sigemptyset(&unblockSet); sigaddset(&unblockSet,SIGINT); sigaddset(&unblockSet,SIGRTMIN);; sigprocmask(SIG_UNBLOCK,&unblockSet,NULL); //Value值会是乱码! //cout << "Receive SIGUSR1, Value = " << receiveNumber << endl; cout << "Unblock, Receive SIGUSR1" << endl; } else if (signalNumber == SIGINT) { cout << "Receive SIGINT, Value = " << receiveNumber << endl; } else if (signalNumber == SIGRTMIN) { cout << "Receive SIGRTMIN, Value = " << receiveNumber << endl; } } //错误退出函数 inline void err_exit(string str); int main() { struct sigaction act; //如果需要使得信号处理程序接收额外数据, //则必须将sa_flags位置为SA_SIGINFO act.sa_flags = SA_SIGINFO; sigemptyset(&act.sa_mask); act.sa_sigaction = onSigAction; //注册信号处理函数 if (sigaction(SIGINT,&act,NULL) < 0) err_exit("sigaction SIGINT"); if (sigaction(SIGRTMIN,&act,NULL) < 0) err_exit("sigaction SIGRTMIN"); if (sigaction(SIGUSR1,&act,NULL) < 0) err_exit("sigaction SIGUSR1"); //将信号SIGINT,SIGRTMIN信号阻塞 sigset_t blockSet; sigemptyset(&blockSet); sigaddset(&blockSet,SIGINT); sigaddset(&blockSet,SIGRTMIN); if (sigprocmask(SIG_BLOCK,&blockSet,NULL) < 0) err_exit("sigprocmask error"); pid_t pid = fork(); if (pid == -1) err_exit("fork error"); else if (pid == 0) { union sigval Value; Value.sival_int = 200; //给父进程发送五次带额外数据的非可靠信号(其实最终只接受到了一次) for (int i = 0; i < 5; ++i) { ++ Value.sival_int; if (sigqueue(getppid(),SIGINT,Value) != 0) err_exit("sigqueue error"); } //给父进程发送五次带额外数据的可靠信号(最终接收到了五次!!!) Value.sival_int = 0; for (int i = 0; i < 5; ++i) { ++ Value.sival_int; if (sigqueue(getppid(),SIGRTMIN,Value) != 0) err_exit("sigqueue error"); } //给父进程发送SIGUSR1信号,解除对SIGINT,SIGRTMIN信号的阻塞 kill(getppid(),SIGUSR1); } while (true) { pause(); } } void err_exit(string str) { perror(str.c_str()); exit(EXIT_FAILURE); }
运行结果:
其实只是收到了一份非可靠信号SIGINT!
附-查看系统限制命令:ulimit
xiaofang@xiaofang:~$ ulimit -a core file size (blocks, -c) unlimited data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 47131 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 47131 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。