|
我写了一个linux进程间信号机制通信的实验
希望实现的功能:用fork( )创建两个子进程,再用系统调用signal( )让父进程捕捉键盘上来的中断信号(即按ctrl+c键);捕捉到中断信号后,父进程用系统调用kill( )向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
Child process1 is killed by parent!
Child process2 is killed by parent!
父进程等待两个子进程终止后,输出如下的信息后终止:
Parent process is killed!
代码如下:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void waiting(),stop();
int wait_mark;
main()
{
int p1,p2,stdout;
while((p1=fork())==-1);
if(p1>0)
{
while((p2=fork())==-1);
if(p2>0)
{
wait_mark=1;
signal(SIGINT,stop);
waiting();
kill(p1,16);
kill(p2,17);
wait(0);
wait(0);
printf("parent process is killed!\n");
exit(0);
}
else
{
wait_mark=1;
signal(17,stop);
printf("%d",SIG_DFL);
waiting();
lockf(stdout,1,0);
printf("child process 2 is killed by parent!\n");
lockf(stdout,0,0);
exit(0);
}
}
else
{
wait_mark=1;
signal(16,stop);
printf("%d",SIG_DFL);
waiting();
lockf(stdout,1,0);
printf("child process 1 is killed by parent!\n");
lockf(stdout,0,0);
exit(0);
}
}
void waiting()
{
while(wait_mark!=0);
}
void stop()
{
wait_mark=0;
}
我加大的那几行肯定是有问题的 signal(sig,fuction)
fuction肯定不可能指向stop ,按道理来说应该指向kill(我认为)
可是我不知道怎么修改这个程序,我是这方面的新手,希望得到哪位大侠的帮助,得到我期望的程序输出!
(按我这样的写法,父进程就直接kill掉了,根本没有对两个子进程发送信号。
执行时按下ctrl+c只是出现:parent process is killed!) |
|