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 128
int main(){
int fdr=-1;
int fdw=-1;
int ret=-1;
char buf[SIZE];
//1.只读方式打开管道fifo1
fdr=open("fifo1",O_RDONLY);
if(-1==fdr){
perror("open");
return 1;
}
printf("以只读方式打开管道fifo1 ok...\n");
//2.只写方式打开管道fifo2
fdw=open("fifo2",O_WRONLY);
if(-1==fdw){
perror("open");
return 1;
}
printf("以只写方式打开管道fifo1 ok...\n");
//3.循环读写
while(1){
//读管道1
memset(buf,0,SIZE);
ret=read(fdr,buf,SIZE);
if(ret<=0){
perror("read");
break;
}
printf("read:%s\n",buf);
//写管道2
memset(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 128
int main(){
int fdr=-1;
int fdw=-1;
int ret=-1;
char buf[SIZE];
//1.只写方式打开管道fifo1
fdw=open("fifo1",O_WRONLY);
if(-1==fdw){
perror("open");
return 1;
}
printf("以只写方式打开管道fifo1 ok...\n");
//2.只读方式打开管道fifo2
fdr=open("fifo2",O_RDONLY);
if(-1==fdr){
perror("open");
return 1;
}
printf("以只读方式打开管道fifo2 ok...\n");
//3.循环读写
while(1){
//写管道fifo1
memset(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;
}
//读管道fifo2
memset(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 talkB
talkA:talkA.c
gcc $< -o $@
talkB:talkB.c
gcc $< -o $@
.PHONY:clean
clean:
rm -rf talkA talkB
执行结果