Write a C program that illustrates how to execute two commands concurrently with a command pipe. Ex: - ls –l | sort

Ram Pothuraju
A pipe is created by calling a pipe() function.
int pipe(int filedesc[2]);
It returns a pair of file descriptors filedesc[0] is open for reading and filedesc[1] is   open for writing. This function returns a 0 if ok & -1 on error.




#include<stdio.h>
#include<stdlib.h>
void main(int argc, char *argv[])
{
  int fd[2],pid,k;
  k=pipe(fd);

if(k==-1)
  {
    perror("pipe");     exit(1);
  }
  pid=fork();
  if(pid==0)
  {
    close(fd[0]);       dup2(fd[1],1);
    close(fd[1]);        execlp(argv[1],argv[1],NULL);
    perror("exec1");
  }
  else
  {
   wait(2);
   close(fd[1]);    dup2(fd[0],0);
   close(fd[0]);
   execlp(argv[2],argv[2],NULL);
   perror("exec1");
 }
}


OUT PUT

Post a Comment

2Comments

Post a Comment