Posted on 2009-01-04 20:04
Prayer 阅读(413)
评论(0) 编辑 收藏 引用 所属分类:
LINUX/UNIX/AIX
/*编制一段程序,使用系统调用fork()创建两个子进程,
再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按Del键),
当捕捉到中断信号后,父进程用系统调用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>
void waiting();
void stop();
int wait_mark;
main()
{
int p1=-1, p2=-1;
//signal(SIGINT, stop); // position A
while ((p1 = fork()) == -1);
if (p1>0)
{ /*parent*/
while ((p2 = fork()) == -1);
if (p2>0)
{ /*parent*/
wait_mark=1;
signal(SIGINT, stop);// position B
waiting();
kill(p1,16); //*send signal 16 to end the process p1
kill(p2,17); //*send signal 17 to end the process p2
wait(0); //*waiting for the ending of p1
wait(0); //*waiting for the ending of p2
printf("parent process is killed!\n");
exit(0); //*quit from the parent process
}
else //*p2 work
{ /*child p2*/
wait_mark=1;
signal(17, stop);
waiting();
lockf(1,1,0);
printf("child process 2 is killed by parent!\n");
lockf(1,0,0);
exit(0); //* p2 quit
}
}
else //*p1 work
{ /*child p1*/
wait_mark=1;
signal(16, stop);
waiting();
lockf(1,1,0);
printf("child process 1 is killed by parent!\n");
lockf(1,0,0);
exit(0); //* p1 quit
}
}
void waiting( )
{
while (wait_mark != 0);
}
void stop()
{
wait_mark=0;
}
又研究了一下,在两个子进程开始就加入signal(SIGINT,SIG_IGN),就满足要求了。看来原来的Ctrl-c信号对所有进程都起作用了,所以得把它给禁了,才能合要求。