随时能够收发

作业需求:

在上述练习的前提下,实现AB进程能够随时收发数据。提示:用多进程或者多线程实现

实现过程:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>

int main(int argc, const char *argv[])
{

	if(mkfifo("./myfifo",06640)<0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	if(mkfifo("./myfifo1",06640)<0)
	
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	int fd=open("./myfifo",O_WRONLY);
	int fd1=open("./myfifo1",O_RDONLY);
	if(fd<0)
	{
		perror("open");
		return -1;
	}
	if(fd1<0)
	{
		perror("open1");
		return -1;
	}
	char str[20]="";

	pthread_t pid;
	pid=fork();
	if(pid>0)
	{
	while(1)
	{
		bzero(str,sizeof(str));
		printf("主请输入>>>");
		fgets(str,sizeof(str),stdin);
		str[strlen(str)-1]='\0';
		write(fd,str,sizeof(str));
		if(strcmp(str,"quit")==0)
		{
			break;
		}
	
	}
	}
	if(pid==0)
	{
		while(1)
		{
	
		bzero(str,sizeof(str));
		read(fd1,str,sizeof(str));
		if(strcmp(str,"quit")==0)
		{
			break;
			
		}
		printf("子程序说%s\n",str);
		}

	}

	return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>

int main(int argc, const char *argv[])
{

	if(mkfifo("./myfifo",06640)<0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	if(mkfifo("./myfifo1",06640)<0)
	
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	int fd=open("./myfifo",O_RDONLY);
	int fd1=open("./myfifo1",O_WRONLY);
	if(fd<0)
	{
		perror("open");
		return -1;
	}
	if(fd1<0)
	{
		perror("open1");
		return -1;
	}
	char str[20]="",str1[20]="quit\n";
	pthread_t pid;
	int i=0;
	pid=fork();

	if(pid>0)
	{
		while(1)
		{
			read(fd,str,sizeof(str));
			if(strcmp(str,"quit")==0)
			{
				break;
			}
			printf("主程序说%s\n",str);
		}
	}
	if(pid==0)
	{
		while(1)
		{

			bzero(str,sizeof(str));
			printf("子请输入>>>");
			fgets(str,sizeof(str),stdin);
			str[strlen(str)-1]='\0';
			write(fd1,str,sizeof(str));
			if(strcmp(str,"quit")==0)
			{
				write(fd,str,sizeof(str));

							break;
			}
			
		}
		

	}

	return 0;
}

实现结果:

ubuntu@ubuntu:08_day$ gcc fifo.c
ubuntu@ubuntu:08_day$ ./a.out 
主请输入>>>子程序说1
子程序说2
子程序说3
1
主请输入>>>2
主请输入>>>4
主请输入>>>5
主请输入>>>quit
ubuntu@ubuntu:08_day$ 


ubuntu@ubuntu:08_day$ gcc fifo2.c
ubuntu@ubuntu:08_day$ ./a.out 
子请输入>>>1
子请输入>>>2
子请输入>>>3
子请输入>>>主程序说1
主程序说2
主程序说4
主程序说5
ubuntu@ubuntu:08_day$ 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值