1、編寫一段程式,使用系統調用fork( )創建兩個子進程,再用系統調用signal( )讓父進 程捕捉鍵盤上來的中斷信號(即按ctrl+c鍵),當捕捉到中斷信號後,父進程用系統調用kill( )向兩個子進程發出信號,子進程捕捉到信號後,分別輸出下列信息後終止: Child process 1 is ...
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