程式間通訊——LINUX

王義強發表於2018-08-30

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!
");
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!
");
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!
");
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

相關文章