10.17作业

1.创建AB进程,实现AB进程的通话。

1)A进程先发送一句话给B进程,B进程接收打印。

2)B进程发送与句话给A进程,A进程接收后打印。

3)重复1)2)步骤即可。

4)当A进程或者B进程发送quit后,AB进程均要结束

将上述练习修改成:AB进程能够随时收发形式

提示:用多线程,多进程,

进程A

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
void * callback1(void* p)
{
	while(1)
	{
		char arr[128]="";
		fgets(arr,128,stdin);
		arr[strlen(arr)-1]='\0';
		write(*(int *)p,arr,128);
	}


}
void * callback2(void *p)
{
	while(1)
	{
		char brr[128]="";
		read(*(int*)p,brr,128);
		printf("%s\n",brr);
	
	}


}
int main(int argc, const char *argv[])
{
	if (mkfifo("fifo_1",0777)<0)
	{
		if(errno!=17)
		{
		perror("mkfifo1");
		return -1;
		}
	}
	if (mkfifo("fifo_2",0777)<0)
	{
		if(errno!=17)
		{
		perror("mkfifo2");
		return -1;
		}
	}
	int fd_1=open("fifo_1",O_RDWR);
	if (fd_1<0)
	{
		perror("open1");
		return -1;
	}
	int fd_2=open("fifo_2",O_RDWR);
	if (fd_2<0)
	{
		perror("open2");
		return -1;
	}

	pthread_t pt_1;
	int p_1=pthread_create(&pt_1,NULL,callback1,&fd_1);
	if (p_1!=0)
	{
		perror("pthread_create");
		return -1;
	}

	pthread_t pt_2;
	int p_2=pthread_create(&pt_2,NULL,callback2,&fd_2);
	if (p_2!=0)
	{
		perror("pthread_create");
		return -1;
	}
	pthread_join(pt_1,NULL);
	pthread_join(pt_2,NULL);
	
	return 0;
}

进程B

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
void * callback1(void* p)
{
	while(1)
	{
		char arr[128]="";
		fgets(arr,128,stdin);
		arr[strlen(arr)-1]='\0';
		write(*(int *)p,arr,128);
	}


}
void * callback2(void *p)
{
	while(1)
	{
		char brr[128]="";
		read(*(int*)p,brr,128);
		printf("%s\n",brr);
	
	}


}
int main(int argc, const char *argv[])
{
	if (mkfifo("fifo_1",0777)<0)
	{
		if(errno!=17)
		{
		perror("mkfifo1");
		return -1;
		}
	}
	if (mkfifo("fifo_2",0777)<0)
	{
		if (errno!=17)
		{
		perror("mkfifo2");
		return -1;
		}
	}
	int fd_1=open("fifo_1",O_RDWR);
	if (fd_1<0)
	{
		perror("open1");
		return -1;
	}
	int fd_2=open("fifo_2",O_RDWR);
	if (fd_2<0)
	{
		perror("open2");
		return -1;
	}

	pthread_t pt_1;
	int p_1=pthread_create(&pt_1,NULL,callback1,&fd_2);
	if (p_1!=0)
	{
		perror("pthread_create");
		return -1;
	}

	pthread_t pt_2;
	int p_2=pthread_create(&pt_2,NULL,callback2,&fd_1);
	if (p_2!=0)
	{
		perror("pthread_create");
		return -1;
	}
	pthread_join(pt_1,NULL);
	pthread_join(pt_2,NULL);
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值