嵌入式 IO day7 使用管道实现AB两个进程之间的相互通信

先创建一个文件夹,在文件夹里创建三个.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;
}

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值