All pastes #944440 Raw Edit

Miscellany

public text v1 · immutable
·published 2008-03-16 02:13 UTC
rendered paste body
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

/* Program should be able to redirect one commands output to the other
 *  commands input. Eg: ls -l | sort -n +4
 */

int main(void) {
   pid_t childpid;
   int fd[2];

   if (( pipe(fd) == -1) || ((childpid = fork() ) == -1)) {             /* setup the pipeline*/
      perror("Failed to setup pipeline");
      return 1;
   }

   if (childpid) {                                  /* ls is the child */
      if (dup2(fd[1] , 1) == -1)
         perror("Failed to redirect stdout of ls");
      else if (( close(fd[1]) == -1) || ( close(fd[0]) == -1))
         perror("Failed to close extra pipe descriptors on ls");
      else {
        execl("/bin/ls", "-l", NULL);
        printf("HI\n");
      }
      return 1;
   }
   if (dup2(fd[0], 0) == -1)               /* word count is the parent */
       perror("Failed to redirect stdin of sort");
   else if ((close(fd[1]) == -1) || (close(fd[0]) == -1))
       perror("Failed to close extra pipe file descriptors on sort");
   else {
     int status;
     status = wait(&status);

     //This always fails because it says the parent never had a child. 
     //How is that even possible?
     if (WIFEXITED(status) != 1 ) { 
       perror("Error: I never had a child!");
     }

     execl("/usr/bin/wc", "-cl", NULL);
      perror("Failed to exec sort");
   }
   return 1;
}