欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

进程间通信——LINUX

程序员文章站 2022-06-11 18:12:09
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