实现两个进程之间的双向通信

1. 通信原理

在这里插入图片描述

2. 通信步骤

1.先创建两个有名管道
2.打开有名管道
3.对有名管道进行读写操作
4.关闭管道

3. 代码实现

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define BUF_SIZE 20

int main()
{
	//mkfifoa
	int ret = -1;
	ret = mkfifo("fifoa",0666);
	if(-1==ret&&EEXIST!=errno)
	{
		printf("mkfifoa error!\r\n");
		return -1;
	}
	printf("create fifoa ok!\r\n");
	//mkfifob
	ret = mkfifo("fifob",0666);
	if(-1==ret&&EEXIST!=errno)
	{
		return -1;
	}
	printf("create fifob ok!\r\n");
	//open fifoa
	int fdw = open("fifoa",O_WRONLY,0666);
	if(-1==fdw)
	{
		printf("open error!\r\n");
		return -1;
	}
	printf("2.open fifoa ok!\r\n");
	//open fifob
	int  fdr = open("fifob",O_RDONLY,0666);
	if(-1==fdr)
	{
		printf("open fifob error\r\n");
		return -1;
	}
	//write read
	char buf[BUF_SIZE] = {0};
	while(1)
	{
		//write
		memset(buf,0,BUF_SIZE);
		printf("Please input:");
		fgets(buf,BUF_SIZE,stdin);
		write(fdw,buf,BUF_SIZE);

		//read
		memset(buf,0,BUF_SIZE);
		read(fdr,buf,BUF_SIZE);
		printf("b->a:%s\r\n",buf);
	}
	//close
	close(fdw);
	close(fdr);
	return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define BUF_SIZE 20

int main()
{
	//open fifoa
	int fdr = open("fifoa",O_RDONLY,0666);
	if(-1==fdr)
	{
		printf("open fifoa error!\r\n");
		return -1;
	}
	printf("2.open fifoa ok!\r\n");
	//open fifob
	int  fdw = open("fifob",O_WRONLY,0666);
	if(-1==fdw)
	{
		printf("open fifob error\r\n");
		return -1;
	}
	//write read
	char buf[BUF_SIZE] = {0};
	while(1)
	{
		//read
		memset(buf,0,BUF_SIZE);
		read(fdr,buf,BUF_SIZE);
		printf("a->b:%s\r\n",buf);
		
		//write
		memset(buf,0,BUF_SIZE);
		printf("Please input:");
		fgets(buf,BUF_SIZE,stdin);
		write(fdw,buf,BUF_SIZE);
	}
	//close
	close(fdw);
	close(fdr);
	return 0;
}

4. 效果展示

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值