先创建一个文件夹,在文件夹里创建三个.c文件
create.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo1",0664)==-1)
{
perror("mkfifo1 error");
return -1;
}
if(mkfifo("./myfifo2",0664)==-1)
{
perror("mkfifo2 error");
return -1;
}
getchar();
system("rm myfifo1");
system("rm myfifo2");
return 0;
}
read.c
#include <myhead.h> int main(int argc, const char *argv[]) { int fd1,fd2; if((fd1=open("./myfifo1",O_RDONLY))==-1) { perror("open error"); return -1; } if((fd2=open("./myfifo2",O_WRONLY))==-1) { perror("open error"); return -1; } pid_t pid =fork(); char buf[128]=""; if(pid<0) { perror("fork error"); return -1; }else if(pid==0) { while(1){ fgets(buf,sizeof(buf),stdin); buf[strlen(buf)-1]='\0'; write(fd2,buf,strlen(buf)); if(strcmp(buf,"quit")==0) { break; } } }else { while(1){ read(fd1,buf,sizeof(buf)); printf("读取的数据为:%s\n",buf); if(strcmp(buf,"quit")==0) { break; } } } close(fd1); close(fd2); return 0; }
write.c
#include <myhead.h> int main(int argc, const char *argv[]) { int fd1,fd2; if((fd1=open("./myfifo1",O_WRONLY))==-1) { perror("open error"); return -1; } if((fd2=open("./myfifo2",O_RDONLY))==-1) { perror("open error"); read -1; } pid_t pid = fork(); char buf[128]=""; if(pid<0) { perror("fork error"); return -1; } else if(pid == 0) { while(1) { read(fd2,buf,sizeof(buf)); printf("读取的数据为:%s\n",buf); if(strcmp(buf,"quit")==0) { break; } } }else{ while(1) { fgets(buf,sizeof(buf),stdin); buf[strlen(buf)-1]='\0'; write(fd1,buf,strlen(buf)); if(strcmp(buf,"quit")==0) { break; } } } close(fd1); close(fd2); return 0; }
运行结果: