A进程
#include <head.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
if(cpid>0)//父进程向管道文件2写
{ int wfd;
if((wfd=open("./myfifo2",O_WRONLY))==-1)
{
ERR_MSG("open");
return -1;
}
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
putchar(10);
printf("B进程请输入:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
write(wfd,buf,sizeof(buf));
if(strcmp(buf,"q")==0)
{
printf("写进程退出\n");
break;
}
}
close(wfd);
}
else if(0==cpid)//子进程从管道文件1读取
{
int rfd;
char buf1[128]="";
if((rfd=open("./myfifo1",O_RDONLY))==-1)
{
ERR_MSG("open");
return -1;
}
while(1)
{
bzero(buf1,sizeof(buf1));
read(rfd,buf1,sizeof(buf1));
if(strcmp(buf1,"q")==0)
{
printf("写进程退出\n");
break;
}
putchar(10);
printf("A进程向B进程输出数据为%s\n",buf1);
}
close(rfd);
}
else
{
ERR_MSG("fork");
return -1;
}
return 0;
}
B进程
#include <head.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
if(cpid>0)//父进程向管道文件1写
{ int wfd;
if((wfd=open("./myfifo1",O_WRONLY))==-1)
{
ERR_MSG("open");
return -1;
}
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
putchar(10);
printf("A进程请输入");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
write(wfd,buf,sizeof(buf));
if(strcmp(buf,"q")==0)
{
printf("写进程退出\n");
break;
}
}
close(wfd);
}
else if(0==cpid)//子进程从管道文件2读取
{
int rfd;
char buf1[128]="";
if((rfd=open("./myfifo2",O_RDONLY))==-1)
{
ERR_MSG("open");
return -1;
}
while(1)
{ int wfd;
if((wfd=open("./myfifo1",O_WRONLY))==-1)
{
ERR_MSG("open");
return -1;
}
char buf[128]="";
bzero(buf1,sizeof(buf1));
read(rfd,buf1,sizeof(buf1));
if(strcmp(buf1,"q")==0)
{
printf("写进程退出\n");
break;
}
putchar(10);
printf("B进程向A进程输出数据为%s\n",buf1);
}
close(rfd);
}
else
{
ERR_MSG("fork");
return -1;
}
return 0;
}