编写程序,演示多进程并发执行和进程软中断、管道通信。
父进程使用系统调用pipe( )建立一个管道,然后使用系统调用fork()创建两个子进程,子进程1和子进程2;子进程1每隔1秒通过管道向子进程2发送数据:I send you x times. (x初值为1,每次发送后做加一操作)子进程2从管道读出信息,并显示在屏幕上。父进程用系统调用signal()捕捉来自键盘的中断信号(即按Ctrl+C键);当捕捉到中断信号后,父进程用系统调用Kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止:
`Child Process l is Killed by Parent!
Child Process 2 is Killed by Parent!`
父进程等待两个子进程终止后,释放管道并输出如下的信息后终止
Parent Process is Killed!
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#define N 50
void stop1(),stop2();
int p1,p2; // 子进程P1,P2
int fd[2]; //无名管道
char buf[N];//消息
void main()
{
if(pipe(fd)<0)//创建管道
{
perror("Fail to pipe");//创建失败,输出提示
exit(EXIT_FAILURE);
}
if(p1=fork())//创建子进程P1
{
if(p2=fork())//创建子进程P2
{
signal(SIGINT,stop1);//等待接受SIGINT信号量
wait(0);//等待P1进程关闭
wait(0);//等待P2进程关闭
printf("parent process is killed!\n");//输出父进程关闭
close(fd[0]);
close(fd[1]);
exit(0);//退出父进程
}
else
{
close(fd[1]); //关闭写管道
int n=0;
signal(SIGINT,SIG_IGN);//忽略SIGINT信号
signal(SIGUSR1,stop2);//接受kill信号,执行stop
while(1)
{
n=read(fd[0],buf,sizeof(buf)+1);//读取管道中的信息
buf[n]='\0';//添加结束标记
printf("child %d receive:'%s.'\n",getpid(),buf);//输出读取的信息
}
}
}
else
{
int i=0;
close(fd[0]);//关闭读管道
signal(SIGUSR1,stop2);//接受kill信号,执行stop
signal(SIGINT,SIG_IGN);//忽略SIGINT信号
while(1){
sprintf(buf,"child %d send %d time",getpid(),i);//写入写入次数到buf
buf[strlen(buf)]='\0';//添加结束标记
write(fd[1],buf,strlen(buf)+1);//将数据写入管道
sleep(1);//等待1s
i++;
}
}
}
void stop1() // signal handler of parent process
{
kill(p1,SIGUSR1);
kill(p2,SIGUSR1);
}
void stop2() // signal handler of parent process
{
close(fd[0]);
close(fd[1]);
//lockf(1,1,0); //锁定
printf("child %d to exit!\n",getpid());
//lockf(1,0,0);//解锁
exit(0);
}