1.习惯用命令创建两个管道 mkfifo fifo1 fifo2
在这里插入图片描述

用户A
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#define SIZE 64
//先读后写
//以只读方式打开管道1
//以只写方式打开管道2
int main(void)
{
int fdr=-1;
int fdw=-1;
int ret=-1;
char buf[SIZE];
//只读方式打开管道1
fdr=open("fifo1",O_RDONLY);
if(-1==fdr){
perror("open");
return 1;
}
printf("以只读方式打开管道1 ok...\n");
fdw=open("fifo2",O_WRONLY);
if(-1==fdw){
perror("open");
return 1;
}
printf("以只写方式打开管道2 ok.....\n");
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;
}
printf("write ret :%d\n",ret);
}
close(fdw);
close(fdr);
return 0;
}
用户B
在这里插入代码片#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#define SIZE 64
//先写后读
//以只写方式打开管道1
//以只读方式打开管道2
int main(void)
{
int fdr=-1;
int fdw=-1;
int ret=-1;
char buf[SIZE];
fdw=open("fifo1",O_WRONLY);
if(-1==fdw){
perror("open");
return 1;
}
printf("以只写方式打开管道1 ok.....\n");
//只读方式打开管道2
fdr=open("fifo2",O_RDONLY);
if(-1==fdr){
perror("open");
return 1;
}
printf("以只读方式打开管道2 ok.....\n");
while(1){
//写管道1
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;
}
printf("write ret :%d\n",ret);
//读管道2
memset(buf,0,SIZE);
ret=read(fdr,buf,SIZE);
if(ret<=0){
perror("read");
break;
}
printf("read: %s\n",buf);
}
close(fdw);
close(fdr);
return 0;
}
细心的伙伴们肯定发现,两者代码只是顺序不同,代码其实一模一样,所以使用有名管道只需要记住调用的管道读写顺序即可。
本文通过两个实例演示了如何使用有名管道进行进程间通信。用户A和用户B分别以不同的顺序进行读写操作,展示了有名管道的基本用法。通过对比两段代码,可以清晰地看到读写顺序对通信的影响。
2036

被折叠的 条评论
为什么被折叠?



