1. View command: Man 2 pipe
2. header file: #include <unistd.h>
3, function prototype: int pipe (int pipefd[2]);
A, pipefd[2]: Nameless Pipe Two file descriptor, array of type int, size is 2,pipefd[0] read end, pipefd[1] is write end
4. Return value:
Success: return 0
Failure: Return-1
5. Function Features:
The nameless pipe is the simplest way to communicate between one-to-one affinity processes, which, since it is a pipe, can be imagined as a pipe that connects two processes
One process is responsible for entering data, while another process is responsible for receiving data, and vice versa.
6, the shortcomings of the Nameless pipeline:
A, no name, and therefore cannot be opened with open ()
b, can only be used to communicate between kinship processes (such as parent-child process, sibling process, grandchild process, etc.)
C, half-duplex working mode, read-write end is separate, pipefd[0] for the read end, pipefd[1] for the write end
D, write operations are not atomic, so they can only be used for one-to-one simple communication
E, cannot use Lseek () to locate
The code below
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <wait.h>
#include <string.h>
#define the size of the LENGTH 50//character array
int main (int argc,char **argv)
{
int status;//process exits with
int pipefd[2];//Two file descriptor for saving nameless pipes, pipefd[0] read, pipefd[1] is write-side
int ret;
pid_t pid;
/* Create a nameless pipe that needs to be created before fork () so that the process can inherit the nameless pipe */
RET = pipe (PIPEFD);
if (ret = =-1)//Create failed
{
Perror ("pipe");
Exit (1);//Abnormal exit
}
PID = fork ();//Create Child process
if (pid! = 0)//parent process, responsible for reading data from nameless pipes
{
Wait (&status);//waits for the child process to exit
Char Buf[length];
Read (pipefd[0],buf,sizeof (BUF));//Read data from a nameless pipe, the Read function blocks
printf ("Information from child process:%s", buf);
}
if (PID = = 0)//Sub-process, responsible for writing data to the nameless pipe
{
Char Buf[length];
Bzero (buf,sizeof (BUF));//emptying buffer
Puts ("Please enter the content you want to send to the parent process:");
Fgets (Buf,sizeof (BUF), stdin);
Write (pipefd[1],buf,sizeof (BUF));//writes data to a nameless pipe
Exit (0);//child process exit
}
Close (pipefd[0]);//Close the read end in the nameless pipe
Close (pipefd[1]);//Close the write end in the nameless pipe
return 0;
}
The Nameless pipe of Linux