进程间通信——LINUX
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
推荐阅读
-
进程间通信——LINUX
-
用linux下的daemon函数来玩守护进程------类似于nohup ./a.out &
-
linux scp命令(主机,服务器间复制文件) 博客分类: linux linuxssh防火墙服务器复制
-
查端口号,查进程号,杀进程 博客分类: Linux
-
弄懂“进程”(下):进程的控制、同步和通信
-
Android的消息机制(线程间通信)
-
使用multiprocesss模块进程通信采用队列方式,子进程run执行完一直不能退出的问题
-
linux:进程间通信之消息队列
-
Linux下查询进程占用内存的方法汇总——top/pmap/ps等
-
Linux下查看进程和线程 博客分类: linux linux