目录
- 1、思路
- 2 、步骤
1、思路
2 、步骤
步骤1:创建两个管道
makefifo fifo1 fifo2
步骤2:编写talkA.c文件
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>#define SIZE 128int main(){int fdr=-1;int fdw=-1;int ret=-1;char buf[SIZE];//1.只读方式打开管道fifo1fdr=open("fifo1",O_RDONLY);if(-1==fdr){perror("open");return 1;}printf("以只读方式打开管道fifo1 ok...\n");//2.只写方式打开管道fifo2fdw=open("fifo2",O_WRONLY);if(-1==fdw){perror("open");return 1;}printf("以只写方式打开管道fifo1 ok...\n");//3.循环读写while(1){//读管道1memset(buf,0,SIZE);ret=read(fdr,buf,SIZE);if(ret<=0){perror("read");break;}printf("read:%s\n",buf);//写管道2memset(buf,0,SIZE);fgets(buf,SIZE,stdin);//去掉最后一个换行符if('\n'==buf[strlen(buf)-1])buf[strlen(buf)-1]='\0';ret=write(fdw,buf,strlen(buf));if(ret<=0){perror("write");break;}}//4.关闭文件描述符close(fdw);close(fdr);return 0;
}
步骤3:编写talkB.c文件
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>#define SIZE 128int main(){int fdr=-1;int fdw=-1;int ret=-1;char buf[SIZE];//1.只写方式打开管道fifo1fdw=open("fifo1",O_WRONLY);if(-1==fdw){perror("open");return 1;}printf("以只写方式打开管道fifo1 ok...\n");//2.只读方式打开管道fifo2fdr=open("fifo2",O_RDONLY);if(-1==fdr){perror("open");return 1;}printf("以只读方式打开管道fifo2 ok...\n");//3.循环读写while(1){//写管道fifo1memset(buf,0,SIZE);fgets(buf,SIZE,stdin);//去掉最后一个换行符if('\n'==buf[strlen(buf)-1])buf[strlen(buf)-1]='\0';ret=write(fdw,buf,strlen(buf));if(ret<=0){perror("write");break;}//读管道fifo2memset(buf,0,SIZE);ret=read(fdr,buf,SIZE);if(ret<=0){perror("read");break;}printf("read:%s\n",buf);}//4.关闭文件描述符close(fdr);close(fdw);return 0;
}
步骤四:编写makefile同时执行talkA.c和talkB.c
all: talkA talkBtalkA:talkA.cgcc $< -o $@talkB:talkB.cgcc $< -o $@.PHONY:cleanclean:rm -rf talkA talkB
执行结果