Linux pipe Function

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.