1. Function description
pipe (create pipeline):
1) Header file #include
2) Define function: int pipe(int filedes[2]);
3) Function description: pipe() The pipeline will be established and the file descriptor will be returned from the parameter filedes array. [Filedes [0] is the read -end of the pipe
FileDes [1] is the writing end of the pipeline.
4) Return value: If successful, return zero, otherwise return -1, and the error reason is stored in errno.
The EMFILE process has exhausted the maximum number of file descriptors
The ENFILE system has no file descriptors available.参 EFAULT parameter FileDes array address illegal.
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; }
Run 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 pipe is read, the pipe is empty. A subsequent read() call will by default block, waiting for some data to be written.非 If you need to be set to non -blocking, you can make the following settings:
FCNTL (FileDes [0], F_SETFL, O_NONBLOCK);
FCNTL (FileDes [1], F_SETFL, O_NONBLOCK);