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 分钟前
Linux-第四章web服务
linux·运维·服务器
悟忧6 分钟前
规避ProseMirror React渲染差异带来的BUG
前端
No0d1es9 分钟前
电子学会青少年软件编程(C/C++)1级等级考试真题试卷(2025年9月)
java·c语言·c++·青少年编程·电子学会·真题·一级
小皮虾12 分钟前
小程序云开发有类似 uniCloud 云对象的方案吗?有的兄弟,有的!
前端·javascript·小程序·云开发
Android疑难杂症16 分钟前
鸿蒙Notification Kit通知服务开发快速指南
android·前端·harmonyos
T___T16 分钟前
全方位解释 JavaScript 执行机制(从底层到实战)
前端·面试
阳懿22 分钟前
meta-llama-3-8B下载失败解决。
前端·javascript·html
爱吃橘的橘猫23 分钟前
如何解决VMware虚拟机中Linux系统终端不显示ens33 inet IP地址的问题
linux·运维·服务器·虚拟机
Qinana23 分钟前
🌊 深入理解 CSS:从选择器到层叠的艺术
前端·css·程序员
IT_陈寒23 分钟前
Python 3.12新特性实测:10个让你的代码提速30%的隐藏技巧 🚀
前端·人工智能·后端