C半双工管道

父进程不断发送消息到子进程,子进程收到消息后发送回应;

 

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "common.h"

int main(void)
{
	int subPid = 0;
	int fd1[2] = {0}, fd2[2] = {0};
	char readBuffer[BUFFER_SIZE];
	char writeBuffer[BUFFER_SIZE];
	int readLength = 0;
	int writeLength = 0;	
	int ret = 0;

	ret = pipe(fd1);
	if (-1 == ret)
	{
		perror("");
		return -1;
	}

	ret = pipe(fd2);
	if (-1 == ret)
	{
		perror("");
		return -1;
	}
	
	subPid = fork();
	if (0 == subPid)
	{
		close(fd1[1]);
		close(fd2[0]);

		while (true)
		{
			readLength = read(fd1[0], readBuffer, BUFFER_SIZE);
			if (0 > readLength)
			{
				perror("");
				return -1;
			}
			else
			{
				printf("CHILD: Received message \"%s\"!\n", readBuffer);
				strcpy(writeBuffer, "Replay from child!");
				write(fd2[1], writeBuffer, strlen(writeBuffer));
			}
		}
	}
	else
	{
		close(fd1[0]);
		close(fd2[1]);
		int sendCount = 0;
		
		while (true)
		{
			sprintf(writeBuffer, "Message from server (total: %d) !", ++sendCount);
			write(fd1[1], writeBuffer, strlen(writeBuffer));
			readLength = read(fd2[0], readBuffer, BUFFER_SIZE);
			if (0 > readLength)
			{
				perror("");
				return -1;
			}
			
			printf("PARENT: Received replay from child \"%s\"!\n", readBuffer);
			usleep(1000000);
		}
	}

	return 1;
}
 

你可能感兴趣的:(c,管道)