6.29 作业

使用管道实现AB两个进程的相互通信(提示:每个程序都可以使用多进程、多线程)

#include <myhead.h>
int main(int argc,const char *argv[])
{
	if(mkfifo("./AtoB",0664))//a输出b的文件
	{
		perror("AtoB error");
		return -1;
	}
	if(mkfifo("./BtoA",0664))//b输出到a的文件
	{
		perror("BtoA error");
		return -1;
	}	
	return 0;
}

A.c

#include <myhead.h>
void *areadb(void *arg)
{
	int f1;
	if((f1=open("./BtoA",O_RDONLY))==-1)//打开文件
	{
		perror("open error1");
		return NULL;
	}
	while(1)
	{
		char a[128]="";
		read(f1,a,sizeof(a));//从b读消息
		if(a[0]=='\n')//只有换行则结束
		{
			break;
		}
		printf("收到消息:%s",a);//输出收到的消息
	}
	close(f1);//关闭文件
	return NULL;
} 
void *awriteb(void *arg)
{
	int f2;
	if((f2=open("./AtoB",O_WRONLY))==-1)//打开文件
	{
		perror("open error2");
		return NULL;
	}
	while(1)
	{
		char buf[128]="";
		fgets(buf,sizeof(buf),stdin);//输入数据
		write(f2,buf,strlen(buf));//往b输出数据
		if(buf[0]=='\n')//不输入则结束
		{
			break;
		}
	}
	close(f2);//关闭文件
	return NULL;
} 
int main(int argc,const char *argv[])
{
	pthread_t tid1,tid2;
	if(pthread_create(&tid1,NULL,areadb,NULL))//第一个线程接受b的数据
	{
		perror("tid1 error");
		return -1;
	}
		
	if(pthread_create(&tid2,NULL,awriteb,NULL))//第二个线程往b写数据
	{
		perror("tid2 error");
		return -1;
	}
	
	pthread_join(tid1,NULL);	
	pthread_join(tid2,NULL);	
	
	return 0;
}

B.c

#include <myhead.h>
void *areadb(void *arg)
{
	int f1;
	if((f1=open("./AtoB",O_RDONLY))==-1)//打开文件
	{
		perror("open error");
		return NULL;
	}
	while(1)
	{
	char a[128]="";
		read(f1,a,sizeof(a));//读取a输出的数据
		if(a[0]=='\n')//关闭
		{
			break;
		}
		printf("收到消息:%s",a);//输出
	}
	close(f1);//关闭文件
	return NULL;
} 
void *awriteb(void *arg)
{
	int f2;
	if((f2=open("./BtoA",O_WRONLY))==-1)//打开文件
	{
		perror("open error");
		return NULL;
	}
	while(1)
	{
	char buf[128]="";
		fgets(buf,sizeof(buf),stdin);//输入数据
		write(f2,buf,strlen(buf));//往管道写数据
		if(buf[0]=='\n')
		{
			break;
		}
	}
	close(f2);//关闭文集
	return NULL;
} 
int main(int argc,const char *argv[])
{
	pthread_t tid1,tid2;
	if(pthread_create(&tid1,NULL,areadb,NULL))//线程读取a
	{
		perror("tid1 error");
		return -1;
	}
	if(pthread_create(&tid2,NULL,awriteb,NULL))//线程往a
	{
		perror("tid2 error");
		return -1;
	}
	pthread_join(tid1,NULL);	
	pthread_join(tid2,NULL);	

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值