IO day6

1> 使用有名管道实现两个进程之间相互通信,提示:可以使用多线程或多进程实现

代码:

1.c

#include <head.h>
int main(int argc, const char *argv[])
{
	pid_t pid = fork();


	int wfd = open("./myfifo1",O_WRONLY);
	int rfd = open("./myfifo2",O_RDONLY);

	if(wfd  == -1)
	{
		perror("open");
		return -1;
	}
	else if(pid == 0)
	{
		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));
			printf("进程1请输入:");
			fgets(buf,sizeof(buf),stdin);
			buf[strlen(buf)-1] = '\0';

			write(wfd,buf,sizeof(buf));

			if(strcmp(buf,"quit") == 0)
			{
				printf("写进程1退出\n");
				break;
			}
		}
	}
	else
	{
		if(rfd == -1)
		{
			perror("open");
			return -1;
		}

		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));

			read(rfd,buf,sizeof(buf));
			if(strcmp(buf,"quit") == 0)
			{
				printf("读进程1退出\n");
				break;
			}
			printf("\n");
			printf("进程1读取的数据:%s\n",buf);
			printf("进程1请输入:");
		}
		
	}
	close(rfd);
	close(wfd);
	return 0;
}

2.c

#include <head.h>
int main(int argc, const char *argv[])
{
	pid_t pid = fork();


	int rfd = open("./myfifo1",O_RDONLY);
	int wfd = open("./myfifo2",O_WRONLY);

	if(pid < 0)
	{
		perror("pid");
		return -1;
	}
	else if(pid == 0)
	{
		if(rfd == -1)
		{
			perror("open");
			return -1;
		}

		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));

			read(rfd,buf,sizeof(buf));
			if(strcmp(buf,"quit") == 0)
			{
				printf("读进程2退出\n");
				break;
			}
			printf("\n");
			printf("进程2读取的数据:%s\n",buf);
			printf("进程2请输入:");
		}
	}
	else
	{
		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));
			printf("进程2请输入:");
			fgets(buf,sizeof(buf),stdin);
			buf[strlen(buf)-1] = '\0';

			write(wfd,buf,sizeof(buf));

			if(strcmp(buf,"quit") == 0)
			{
				printf("写进程2退出\n");
				break;
			}
		}

	}
	close(rfd);
	close(wfd);
	return 0;
}

create.c

#include <head.h>
int main(int argc, const char *argv[])
{
	if(mkfifo("./myfifo1",0664) != 0)
	{
		perror("myfifo");
		return -1;
	}
	if(mkfifo("./myfifo2",0664) != 0)
	{
		perror("myfifo");
		return -1;
	}
	while(1)
	{}
	return 0;
}

运行结果:

2> 思维导图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值