1、编写一段程序,使用系统调用fork( )创建两个子进程,再用系统调用signal( )让父进 程捕捉键盘上来的中断信号(即按ctrl+c键),当捕捉到中断信号后,父进程用系统调用kill( )向两个子进程发出信号,子进程捕捉到信号后,分别输出下列信息后终止:
Child process 1 is killed by parent!
Child process 2 is killed by parent!
父进程等待两个子进程终止后,输出以下信息后终止:
Parent process is killed!
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int wait_mark;
void waiting(),stop();
void main()
{int p1, p2;
signal(SIGINT,stop);
while((p1=fork())==-);
if(p1>) /*在父进程中*/
{①
while((p2=fork())==-);
If(p2>) /*在父进程中*/
{ ②
wait_mark=;
waiting();
kill(p1,);
kill(p2,);
wait( );
wait( );
printf("parent process is killed!\n");
exit();
}
else /*在子进程2中*/
{
wait_mark=;
signal(,stop);
waiting();
lockf(,,);
printf("child process 2 is killed by parent!\n");
lockf(,,);
exit();
}
}
else /*在子进程1中*/
{
wait_mark=;
signal(,stop);
waiting();
lockf(,,);
printf("child process 1 is killed by parent!\n");
lockf(,,);
exit();
}
}
void waiting()
{
while(wait_mark!=);
}
void stop()
{
wait_mark=;
}
⑴运行程序并分析结果。
^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