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;
}
相关推荐
一叶之秋141213 小时前
Linux基础IO
linux·运维·服务器
霍理迪13 小时前
CSS——背景样式以及雪碧图、渐变
前端·css
jump_jump17 小时前
基于 Squoosh WASM 的浏览器端图片转换库
前端·javascript·性能优化
小二·20 小时前
前端监控体系完全指南:从错误捕获到用户行为分析(Vue 3 + Sentry + Web Vitals)
前端·vue.js·sentry
野生的码农20 小时前
码农的妇产科实习记录
android·java·人工智能
Web极客码20 小时前
如何在Ubuntu服务器上安装和配置BIND9
服务器·数据库·ubuntu
吳所畏惧20 小时前
Linux环境/麒麟V10SP3下离线安装Redis、修改默认密码并设置Redis开机自启动
linux·运维·服务器·redis·中间件·架构·ssh
毕设源码-赖学姐21 小时前
【开题答辩全过程】以 高校人才培养方案管理系统的设计与实现为例,包含答辩的问题和答案
java
阿珊和她的猫21 小时前
`require` 与 `import` 的区别剖析
前端·webpack
一起努力啊~21 小时前
算法刷题-二分查找
java·数据结构·算法