create.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
//创建管道文件A->B
if(mkfifo("./AtoB",0664)==-1){
perror("mkfifo error");
return -1;
}
//创建管道文件B->A
if(mkfifo("./BtoA",0664)==-1){
perror("mkfifo error");
return -1;
}
return 0;
}
userA
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid<0){
return -1;
}else if(pid==0){ //写入AtoB
int fd;
char buf[128]="";
if((fd=open("./AtoB",O_WRONLY))==-1){
return -1;
}
while(1){
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(fd,buf,strlen(buf));
if(strcmp(buf,"quit")==0){
break;
}
}
close(fd);
exit(EXIT_SUCCESS);
}else{ //读取BtoA
int fd;
char buf[128]="";
if((fd=open("./BtoA",O_RDONLY))==-1){
return -1;
}
while(1){
read(fd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0){
break;
}
printf("userA读取到的%s\n",buf);
}
close(fd);
wait(NULL);
}
return 0;
}
userB.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid<0){
return -1;
}else if(pid==0){ //写入BtoA
int fd;
char buf[128]="";
if((fd=open("./BtoA",O_WRONLY))==-1){
return -1;
}
while(1){
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(fd,buf,strlen(buf));
if(strcmp(buf,"quit")==0){
break;
}
}
close(fd);
exit(EXIT_SUCCESS);
}else{ //读取AtoB
int fd;
char buf[128]="";
if((fd=open("./AtoB",O_RDONLY))==-1){
return -1;
}
while(1){
read(fd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0){
break;
}
printf("userB读取到的%s\n",buf);
}
close(fd);
wait(NULL);
}
return 0;
}
运行结果