C program for pipe in Linux

Server Side ProgrammingC++Programming

Here, we will create a C program for pipe in Linux. In this program, we will read some text from the input stream and then print it to the output screen.

First, let’s learn basics about pipe in Linux

Pipe is used to transfer data, it can be used for communication between process/ command/ program for transferring standard output between two in Linux or Unix based system.

One important thing to be noted is that pipes are unidirectional i.e. data can either flow from left to right or from right to left in the program.

Here, we will create a pipe that will read input from users and print it to the output screen. The implementation takes an array of size 2 which are used to take input arr[0] and returning output arr[1].

C program for pipe in Linux

Example

 Live Demo

#include <errno.h>
#include<string.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(){
   int Pipe[2];
   char string[100];
   if (pipe(Pipe) == -1){
      perror("Filed to create pipe");
      exit(1);
   }
   scanf("%s", string);
   write(Pipe[1], string, strlen(string)+1);
   printf("\n");
   read(Pipe[0], string, 5);
   printf("%s", string);
}

Output

input: TutorialsPoint
TutorialsPoint
raja
Published on 17-Jul-2020 12:58:41
Advertisements