进程通信signal()实验

调用fork()创建两个子进程,父进程接受SIGINT信号中断,之后发送16和17中断子进程。

 1 #include <sys/wait.h>
 2 #include <sys/types.h>
 3 #include <unistd.h>
 4 #include <signal.h>
 5 #include <iostream>
 6 #include <cstdlib>
 7 using namespace std;
 8 int flag;
 9 void stop(int signo) {
10     flag = 0;
11     if (signo == SIGINT){
12         cout << "recv SIGINT" << endl;
13     }
14     else if (signo == 16) {
15         cout << "recv 16" << endl;
16     }
17     else if (signo == 17) {
18         cout << "recv 17" << endl;
19     }
20 }
21 
22 int main()
23 {
24     int pid1;
25     int pid2;
26     if ((pid1 = fork()) < 0) {
27         cerr << "fork1 error" << endl;
28         exit(0);
29     }
30     if (pid1 > 0) {
31         if ((pid2 = fork()) < 0) {
32             cerr << "fork2 error" << endl;
33             exit(0);
34         }
35         if (pid2 > 0) {
36             flag = 1;
37             signal(SIGINT, stop);
38             while (flag);
39             kill(pid1, 16);
40             kill(pid2, 17);
41             wait(NULL);
42             wait(NULL);
43             cout << "Parent process is killed !!" << endl;
44             exit(0);
45         }
46         else {
47             flag = 1;
48             signal(17, stop);
49             while (flag);
50             cout << "c2" << endl;
51             exit(0);
52         }
53     }
54     else {
55         flag = 1;
56         signal(16, stop);
57         while (flag);
58         cout << "c1" << endl;
59         exit(0);
60     }
61     
62     return 0;
63 }

运行后打开另一个终端,用ps aux获取进程pid号

kill -s SIGINT (pid)

向父进程发送SIGINT中断信号。

结果:

 

转载于:https://www.cnblogs.com/Zzz-y/p/8928358.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值