IO进程线程 day6

发布时间:2024年01月08日

创建两个有名管道文件:

#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数据

#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数据

#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;
}

?

文章来源:https://blog.csdn.net/fj199121/article/details/135468045
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。