Home  >  Article  >  php教程  >  Linux pipe function

Linux pipe function

高洛峰
高洛峰Original
2016-12-13 11:34:301578browse

1. Function description

pipe (create pipeline):
1) Header file #includef55648144b4a1c5cce7ad2f6519be0f3
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.

Error code:

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);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn