Inter-process communication method: pipe (2) ------- unnamed pipe

Compared with named pipes, unnamed pipes have no file descriptors in the file directory tree, so in order to complete inter-process communication, unnamed pipes must rely on the file descriptors shared by the parent and child processes before fork. In the same way, the anonymous pipe is a one-way data channel for half-duplex communication.

Restriction of unnamed pipes: Unnamed pipes can only be used between processes with kinship (parent-child process, sibling process).

Creation of an unnamed pipe (created by the parent process): int pipe(int fd[2]); f[0] points to the read end of the pipe, and f[1] points to the write end.


use:

        

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>cc
#include <ctype.h>

#define MAXLEN 256

intmain()
{
	int fd1[2];
	int fd2[2];
	char tmp[MAXLEN] = {0};
	int check1 = pipe(fd1);
	int check2 = pipe(fd2);
	if( check1 == -1 || check2 == -1 )
	{
		perror("check");
		exit(0);
	}

	pid_t pid = fork();
	if( pid == 0 )//The child process receives the data of the parent process and processes the data, and then passes it to the parent process
	{
		int i = 0 ;
		int co = 0 ;
		close(fd1[1]);
		close(fd2[0]);
		while(1)
		{
			co = read(fd1[0],tmp,MAXLEN);
			if( co == 0 || strncmp(tmp,"end",3) == 0 )
				break ;
			for( i = 0 ; i < co ;++i )
			{
				if( islower(tmp[i]) )
					tmp[i] = tmp[i] - 'a' + 'A';
			}
			write(fd2[1],tmp,strlen(tmp));
			memset(tmp,0,MAXLEN);
		}
		close(fd1[0]);
		close(fd2[1]);
	}
	else//The parent process receives the user input data, passes it to the child process, and then receives the data output processed by the child process
	{
		close(fd1[0]);
		close(fd2[1]);
		while(1)
		{
			printf("father input:");
			fgets(tmp,MAXLEN-1,stdin);
			write(fd1[1],tmp,strlen(tmp)-1);
			if( strncmp(tmp,"end",3) == 0 )
				break ;
			memset(tmp,0,MAXLEN);
			read(fd2[0],tmp,MAXLEN);
			printf("father output:%s\n",tmp);
		}
		close(fd1[1]);
		close(fd2[0]);
	}
	exit(0) ;
}


        operation result:

       

        Note for reading and writing to unnamed pipes:

        1. The running order of the parent and child processes cannot be guaranteed.

        2. It is half-duplex like a named pipe, so a process should not read + write to an unnamed pipe at the same time.

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324522553&siteId=291194637