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;
}
相关推荐
武子康1 小时前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
椰椰椰耶3 小时前
【Spring】拦截器详解
java·后端·spring
没有bug.的程序员4 小时前
JAVA面试宝典 - 《MyBatis 进阶:插件开发与二级缓存》
java·面试·mybatis
brzhang4 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
止观止4 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms4 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登4 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
saynaihe5 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
小蜜蜂爱编程5 小时前
ubuntu透网方案
运维·服务器·ubuntu