Unix Piping using Fork and Dup

Posted by Jacob on Stack Overflow See other posts from Stack Overflow or by Jacob
Published on 2010-04-07T03:58:10Z Indexed on 2010/04/07 4:03 UTC
Read the original article Hit count: 313

Filed under:
|
|
|

Lets say within my program I want to execute two child processes, one to to execute a "ls -al" command and then pipe that into "wc" command and display the output on the terminal. How can I do this using pipe file descriptors so far the code I have written: An example would be greatly helpful

int main(int argc, char *argv[]) {
int pipefd[2]


  pipe(pipefd2);
  if ((fork()) == 0) {
     dup2(pipefd2[1],STDOUT_FILENO);
     close(pipefd2[0]);
     close(pipefd2[1]);
     execl("ls", "ls","-al", NULL);
     exit(EXIT_FAILURE);
  } 

  if ((fork()) == 0){
      dup2(pipefd2[0],STDIN_FILENO);
      close(pipefd2[0]);
      close(pipefd2[1]);
      execl("/usr/bin/wc","wc",NULL);
      exit(EXIT_FAILURE);
  }
  close(pipefd[0]);
  close(pipefd[1]);
  close(pipefd2[0]);
  close(pipefd2[1]);

}

© Stack Overflow or respective owner

Related posts about unix-programming

Related posts about c