C program for pipe in Linux

Working and implementation of Pipe in Linux.

Prerequisite : Pipe in Linux

Approach : Pipe is highly used in Linux. Basically, pipe has 2 parts, one part is for writing and another is used for reading. So, an array of size 2 is taken. a[1] is used for writing and a[0] for reading.After reading from pipe, program will show output on console.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to implement pipe in Linux
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
  
int main()
{
    // array of 2 size a[0] is for reading 
    // and a[1] is for writing over a pipe 
    int a[2]; 
  
    // opening of pipe using pipe(a)   
    char buff[10];
    if (pipe(a) == -1) 
    {
        perror("pipe"); // error in pipe
        exit(1); // exit from the program
    }
  
    // writing a string "code" in pipe
    write(a[1], "code", 5); 
    printf("\n");
  
    // reading pipe now buff is equal to "code"
    read(a[0], buff, 5);
  
    // it will print "code"
    printf("%s", buff); 
}

chevron_right


Output :

More examples on pipe()



My Personal Notes arrow_drop_up

[ Intern at GeeksForGeeks ] I am a Computer Science and Engineering Undergraduate at MNNIT Allahabad I love to do competitive programming and software development I like to contribute open source projects I always believe in learning new technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.