通过有名管道实现AB进程对话

一、要求实现AB进程对话

  1. A进程先发送一句话给B进程,B进程接收后打印
  2. B进程再回复一句话给A进程,A进程接收后打印
  3. 重复1.2步骤,当收到quit后,要结束AB进程

A进程

#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, const char *argv[])
{
	if(mkfifo("./fifo_A",0664) < 0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	if(mkfifo("./fifo_B",0664) < 0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}

	int fd_A = open("./fifo_A",O_WRONLY);
	if(fd_A < 0)
	{
		perror("open");
		return -1;
	}
	int fd_B = open("./fifo_B",O_RDONLY);
	if(fd_B < 0)
	{
		perror("open");
		return -1;
	}
	printf("open success\n");
	char buf[128] = "";
	while(1)
	{
		scanf("%s",buf);
		write(fd_A,buf,sizeof(buf));

		bzero(buf,sizeof(buf));
		read(fd_B,buf,sizeof(buf));
		if(strcmp(buf,"quit") == 0)
		{
			write(fd_A,buf,sizeof(buf));
			break;
		}
		printf("%s\n",buf);
	
	}
	close(fd_A);
	close(fd_B);
	return 0;
}

B进程 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc, const char *argv[])
{
	if(mkfifo("./fifo_A",0664) < 0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	if(mkfifo("./fifo_B",0664) < 0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}

	int fd_A = open("./fifo_A",O_RDONLY);
	if(fd_A < 0)
	{
		perror("open");
		return -1;
	}
	int fd_B = open("./fifo_B",O_WRONLY);
	if(fd_B < 0)
	{
		perror("open");
		return -1;
	}
	printf("open success\n");
	char buf[128] = "";
	while(1)
	{
		bzero(buf,sizeof(buf));
		read(fd_A,buf,sizeof(buf));
		if(strcmp(buf,"quit") == 0)
		{
			write(fd_B,buf,sizeof(buf));
			break;
		}
		printf("%s\n",buf);

		scanf("%s",buf);
		write(fd_B,buf,sizeof(buf));
	}
	close(fd_A);
	close(fd_B);
	return 0;
}

你可能感兴趣的:(IO进程线程练习,服务器,linux,运维)