1、 完成一个简单的例子:
进程间的信号通信:
源文件:sigtest.c
#include<sys/file.h>
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
voidwaiting();
voidstop();
intwait_mark;
char *pname;
main()
{
intp1,p2,stdout;
while((p1=fork())==-1);
if(p1>0)//父进程
{
while((p2=fork())==-1);
if(p2>0)//父进程
{
Pname=“paraent process“;
signal(SIGINT,stop);
wait_mark=1;
waiting();
printf(“I’m %s,get singal!\n”,pname);
sleep(2);
printf(“I’m %s,I’m sending singal 10 to p1\n”,pname);
kill(p1,10);//向P1发送信号10
kill(p2,12);//向P2发送信号12
wait(0);//等待子进程退出
sleep(2);
printf(“I’m %s,I’m sending singal 12 to p1\n”,pname);
wait(0);//等待子进程退出
sleep(2);
//printf(" parent process is killed !\n" );
printf(“I’m %s,I’m quiting\n”,pname);
exit(0);
}
else //2号子进程
{
signal(SIGINT,SIG_IGN);
pname=”childprocess 2”;
wait_mark=1;
signal(12,stop);
waiting();
printf("chlidprocess 2 is killed by parent!\n" );
exit(0);
}
}
else//1号子进程
{
signal(SIGINT,SIG_IGN);
pname=”childprocess 1”;
wait_mark=1;
signal(10,stop);
waiting();
printf("chlidprocess 1 is killed by parrent!\n" );
exit(0);
}
}
voidwaiting()
{
while(wait_mark == 1)//更改全局变量wait_mark,退出等待循环
{sleep(2);
Printf(“I’m %s,wainting singal!\n”,pname);
}
}
voidstop()
{
wait_mark=0;//更改全局变量wait_mark,使waiting函数退出
}
观察并解释上述程序的运行结果。
修改后的:
创建两个子进程,父进程捕捉键盘上来的中断信号(即按^c键);捕捉到中断信号后,父进程向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:Child process1 is killed by parent! Child process2 is killed byparent!父进程等待两个子进程终止后,输出如下的信息后终止:Parent process iskilled!