IO进程线程 day6

创建两个有名管道文件:

cpp 复制代码
#include<my_head.h>

int main(int argc, const char *argv[])
{
	//创建两个有名管道文件
	if(mkfifo("./myfifo1",0664) != 0)
	{
		perror("mkfifo pipe1 error");
		return -1;
	}
	if(mkfifo("./myfifo2",0664) != 0)
	{
		perror("mkfifo pipe2 error");
		return -1;
	}
	printf("管道文件创建成功\n");
	getchar();
	system("rm myfifo1");
	system("rm myfifo2");
	
	return 0;
}

文件1:父进程读取管道2数据,子进程写入管道1数据

cpp 复制代码
#include<my_head.h>

int main(int argc, const char *argv[])
{
	//创建子进程
	int pid;
	pid = fork();
	if(pid == 0)
	{
		int wfd = -1;
		if((wfd = open("./myfifo1",O_WRONLY)) == -1)
		{
			perror("open error");
			return -1;
		}
		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));
			printf("请输入>>>");
			fflush(stdout);
			read(0,buf,sizeof(buf));
			buf[strlen(buf)-1] = 0;
			//子进程用管道1的写端
			write(wfd,buf,strlen(buf));
			if(strcmp(buf,"quit") == 0)
				break;

		}
		close(wfd);
		exit(0);
	}
	else if(pid > 0)
	{
		int rfd = -1;
		if((rfd = open("./myfifo2",O_RDONLY)) == -1)
		{
			perror("open error");
			return -1;
		}

		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));
			//父进程用管道2的读端
			read(rfd,buf,sizeof(buf));
			printf("收到消息:%s\n",buf);
			if(strcmp(buf,"quit") == 0)
				break;
		}
		close(rfd);
		wait(0);
	}
	else
	{
		perror("fork error");
		return -1;
	}

	return 0;
}

文件1:父进程读取管道1数据,子进程写入管道2数据

cpp 复制代码
#include<my_head.h>

int main(int argc, const char *argv[])
{
	//创建子进程
	int pid;
	pid = fork();
	if(pid == 0)
	{
		int wfd = -1;
		if((wfd = open("./myfifo2",O_WRONLY)) == -1)
		{
			perror("open error");
			return -1;
		}
		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));
			printf("请输入>>>");
			fflush(stdout);
			read(0,buf,sizeof(buf));
			buf[strlen(buf)-1] = 0;
			//子进程用管道1的写端
			write(wfd,buf,strlen(buf));
			if(strcmp(buf,"quit") == 0)
				break;

		}
		close(wfd);
		exit(0);
	}
	else if(pid > 0)
	{
		int rfd = -1;
		if((rfd = open("./myfifo1",O_RDONLY)) == -1)
		{
			perror("open error");
			return -1;
		}

		char buf[128] = "";
		while(1)
		{
			bzero(buf,sizeof(buf));
			//父进程用管道2的读端
			read(rfd,buf,sizeof(buf));
			printf("收到消息:%s\n",buf);
			if(strcmp(buf,"quit") == 0)
				break;
		}
		close(rfd);
		wait(0);
	}
	else
	{
		perror("fork error");
		return -1;
	}

	return 0;
}
相关推荐
coderSong256826 分钟前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
Mr_Air_Boy1 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
ABB自动化2 小时前
for AC500 PLCs 3ADR025003M9903的安全说明
服务器·安全·机器人
coding随想2 小时前
JavaScript ES6 解构:优雅提取数据的艺术
前端·javascript·es6
努力学习的小廉2 小时前
深入了解linux系统—— 进程池
linux·运维·服务器
年老体衰按不动键盘2 小时前
快速部署和启动Vue3项目
java·javascript·vue
小小小小宇2 小时前
一个小小的柯里化函数
前端
灵感__idea2 小时前
JavaScript高级程序设计(第5版):无处不在的集合
前端·javascript·程序员
咖啡啡不加糖2 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存