Skip to content
Related Articles

Related Articles

Improve Article
C program for pipe in Linux
  • Difficulty Level : Basic
  • Last Updated : 26 Apr, 2018

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.




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

Output :

More examples on pipe()

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.

My Personal Notes arrow_drop_up
Recommended Articles
Page :