【无标题】

 


//创建管道函数
#include<myhead.h>

int main(int argc, const char *argv[])
{
	//创建两个管道文件
	if(mkfifo("./myfifo1",0664)==-1)
	{
		perror("mkdir error");
		return -1;
	}
	if(mkfifo("./myfifo2",0664)==-1)
	{
		perror("mkdir error");
		return -1;
	}
	//阻塞
	getchar();

	system("rm myfifo1");
	system("rm myfifo2");
	return 0;
}
//第一个收发函数
#include<myhead.h>

int main(int argc, const char *argv[])
{
	pid_t pid=fork();
	//父进程
	if(pid>0)
	{
	//打开管道文件1
	int wfd=-1;
	if((wfd=open("./myfifo1",O_WRONLY))==-1)
	{
		perror("open error");
		return -1;
	}
	char wbuf[128]="";
	while(1)
	{
		printf("请输入>>>");
		fgets(wbuf,sizeof(wbuf),stdin);
		wbuf[strlen(wbuf)-1]=0;
		//将数据写入管道1
		write(wfd,wbuf,strlen(wbuf));
		//判断结果
		if(strcmp(wbuf,"quit")==0)
		{
			break;
		}
	}
	close(wfd);
	wait(NULL);//阻塞回收子进程
	}
	else if(pid==0)
	{
		
		//以只读打开管道文件2

		int rfd2=-1;
		if((rfd2=open("./myfifo2",O_RDONLY))==-1)
		{
			perror("open error");
			return -1;
		}
		//定义容器
		char rbuf2[128]="";
		while(1)
		{
			//清空数组
			bzero(rbuf2,sizeof(rbuf2));
			//读取管道中的数据
			read(rfd2,rbuf2,sizeof(rbuf2));

			//输出结果
			printf("\n收到的数据为:%s\n",rbuf2);

			//判断结果
			if(strcmp(rbuf2,"quit")==0)
			{
				break;
			}
		}
		close(rfd2); 
		exit(EXIT_SUCCESS);
	}
	else
	{
		perror("fork error");
		return -1;
	}
	return 0;
}
//第二个收发函数
#include<myhead.h>

int main(int argc, const char *argv[])
{
	pid_t pid=fork();
	if(pid>0)
	{	//以只读打开管道文件1
	int rfd=-1;
	if((rfd=open("./myfifo1",O_RDONLY))==-1)
	{
		perror("open error");
		return -1;
	}
	//定义容器
	char rbuf[128]="";
	while(1)
	{
		//清空数组
		bzero(rbuf,sizeof(rbuf));
		//读取管道中的数据
		read(rfd,rbuf,sizeof(rbuf));

		//输出结果
		printf("\n收到的数据为:%s\n",rbuf);

		//判断结果
		if(strcmp(rbuf,"quit")==0)
		{
			break;
		}
	}
	close(rfd);
	wait(NULL);//阻塞回收子进程
	}
	else if(pid==0)
	{
	//打开管道文件2
	int wfd2=-1;
	if((wfd2=open("./myfifo2",O_WRONLY))==-1)
	{
		perror("open error");
		return -1;
	}
	char wbuf2[128]="";
	while(1)
	{
		printf("请输入>>>");
		fgets(wbuf2,sizeof(wbuf2),stdin);
		wbuf2[strlen(wbuf2)-1]=0;
		//将数据写入管道1
		write(wfd2,wbuf2,strlen(wbuf2));
		//判断结果
		if(strcmp(wbuf2,"quit")==0)
		{
			break;
		}
	}
	close(wfd2);
	exit(EXIT_SUCCESS);
	}
	else
	{
		perror("fork error");
		return -1; 
	}
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值