1. Function Description
Pipe (pipeline creation ):
1) header file # include <unistd. h>
2) define the function: int pipe (INT filedes [2]);
3) Function Description: pipe () creates an MPS queue and returns the file description words from the filedes array.
Filedes [0] is the read end in the pipeline
Filedes [1] is the write end of the MPs queue.
4) Return Value: if it succeeds, zero is returned. Otherwise,-1 is returned. The error cause is stored in errno.
Error code:
The emfile process has used up the maximum number of file descriptions
The enfile system does not have a file description word available.
The filedes array address of the efault parameter is invalid.
2. Example
#include <unistd.h>#include <stdio.h>int main( void ){ int filedes[2]; char buf[80]; pid_t pid; pipe( filedes ); pid=fork(); if (pid > 0) { printf( "This is in the father process,here write a string to the pipe.\n" ); char s[] = "Hello world , this is write by pipe.\n"; write( filedes[1], s, sizeof(s) ); close( filedes[0] ); close( filedes[1] ); } else if(pid == 0) { printf( "This is in the child process,here read a string from the pipe.\n" ); read( filedes[0], buf, sizeof(buf) ); printf( "%s\n", buf ); close( filedes[0] ); close( filedes[1] ); } waitpid( pid, NULL, 0 ); return 0;}
Running result:
[Root @ localhost SRC] # GCC pipe. c
[Root @ localhost SRC] #./A. Out
This is in the child process, here read a string from the pipe.
This is in the father process, here write a string to the pipe.
Hello world, this is write by pipe.
When the data in the MPs queue is read, the MPs queue is empty. A subsequent read () call will be blocked by default, waiting for some data to be written.
If you want to set it to non-blocking, you can do the following:
Fcntl (filedes [0], f_setfl, o_nonblock );
Fcntl (filedes [1], f_setfl, o_nonblock );