进程间通信——LINUX

2018-09-01 05:36:18来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

1、编写一段程序,使用系统调用fork( )创建两个子进程,再用系统调用signal( )让父进  程捕捉键盘上来的中断信号(即按ctrl+c键),当捕捉到中断信号后,父进程用系统调用kill( )向两个子进程发出信号,子进程捕捉到信号后,分别输出下列信息后终止:  

Child process 1 is killed by parent!

Child process 2 is killed by parent!

父进程等待两个子进程终止后,输出以下信息后终止:

Parent process is killed!

 1 #include<stdio.h>
 2 #include<signal.h>
 3 #include<unistd.h>
 4 #include<sys/types.h>
 5 #include<sys/wait.h>
 6 int wait_mark;
 7 void waiting(),stop();
 8 void main()
 9 {int  p1, p2;
10 signal(SIGINT,stop);
11 while((p1=fork())==-1);
12 if(p1>0)                            /*在父进程中*/
13 {①
14 while((p2=fork())==-1);
15            If(p2>0)                    /*在父进程中*/
16             { ②
17                   wait_mark=1;
18                  waiting(0);
19                 kill(p1,10);
20                 kill(p2,12);
21                 wait( );
22                wait( );
23                printf("parent process is killed!\n");
24                exit(0);
25             }
26            else                        /*在子进程2中*/
27            {
28 wait_mark=1;
29 signal(12,stop);
30 waiting();
31 lockf(1,1,0);
32 printf("child process 2 is killed by parent!\n");
33 lockf(1,0,0);
34 exit(0);
35 }
36 } 
37 else                        /*在子进程1中*/
38 {
39       wait_mark=1;
40       signal(10,stop);
41       waiting();
42       lockf(1,1,0);
43       printf("child process 1 is killed by parent!\n");
44       lockf(1,0,0);
45       exit(0);
46 }
47 }
48 void waiting()
49 {
50    while(wait_mark!=0);
51 }
52 void stop()
53 {
54    wait_mark=0;
55 }

 

⑴运行程序并分析结果。

^C

child process 2 is killed by parent!

child process 1 is killed by parent!

parent process is killed!

 

如果把signal(SIGINT,stop)放在①号和②号位置,结果会怎样并分析原因。

1-

^C

child process 2 is killed by parent!

parent process is killed!

 

2-

^C

parent process is killed!

 

该程序段前面部分用了两个wait(0),为什么?

关掉后一个wait

^C

child process 1 is killed by parent!

parent process is killed!root@kali:~/wyq/S4#

child process 2 is killed by parent!gcc -o S4_1-3.out S4_1-3.c

 

两个都关掉

^C

parent process is killed!root@kali:~/wyq/S4#

child process 2 is killed by parent!

child process 1 is killed by parent!^C

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:keepalived

下一篇:进程管理工具使用