#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(void){
int p,i,fd[2],fs[2];
int re1=0;
int re2=0;
char fd_out[50];
char fs_out[50];
char fd_in[50]=“child send to parent : Hello,parent!”;
char fs_in[50]=“parent respond to child:Received.”;
/若无名管道创建失败,提示错误信息。/
while(pipe(fd) < 0 || pipe(fs)<0)
{
perror(“Fail to create pipe!”);
exit(EXIT_FAILURE);
}
/若子进程创建失败,提示错误信息。/
while((p = fork())<0)
{
perror(“Fail to create child process!”);
exit(EXIT_FAILURE);
}
/子进程创建成功/
if(p==0)
{
while(re1<0)
{
printf(“Receive Error!”);
exit(EXIT_FAILURE);
}
/从管道fd的写口写入数据,并从fs的读口读数据/
close (fd[0]);//关闭管道fd的读口
close (fs[1]);//关闭管道fs的写口
for(i=0;i<5;i++){
write(fd[1],fd_in,50);
sleep(1);
re1=read(fs[0],fs_out,50);
if(re1>0)
printf("%s\n",fs_out);
else if(re1 == 0)
printf("First\n");
}
exit(EXIT_SUCCESS);
}else{
/*从管道fs的写口写入数据,并从fd的读口读数据*/
for(i=0;i<5;i++){
close (fd[1]);//关闭fd的写口
close (fs[0]);//关闭fs的读口
re2=read(fd[0],fd_out,50);
if(re2>0)
{
sleep(1);
printf("%s\n",fd_out);
write(fs[1],fs_in,50);
}
}
}
sleep(1);
printf("------------------Program-----End-------------------\n");
}