/* This program creates a new process and provides a simple pipe to
   allow the parent to communicate with the child 
   Version 4 -- using exec's to run external programs*/

#include <sys/types.h>
#include <unistd.h>          
#include <stdio.h>

int main (void)
{  int fd[2];             /* provide file descriptor pointer array for pipe */
                          /* within pipe:
                                 fd[0] will be input end
                                 fd[1] will be output end */

   pid_t pid1, pid2;      /* process id's for each child */

   int value, value1;     /* integer values for writing and reading */
   
   if (pipe (fd) < 0)     /* create pipe and check for an error */
     { perror("pipe error");
       exit (1);
     }

   if ((pid1 = fork()) < 0)  /* apply fork and check for error */
     { perror ("error in fork");  
       exit (1);
     }

   if (0 == pid1)             
     { /* processing for child */
       printf ("The first child process is active.\n");
       close (fd[1]);       /* close output end, leaving input open */
       /* set standard input to pipe */
       if (fd[0] !=  STDIN_FILENO) 
         { if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO)
             { perror("dup2 error for standard input");
               exit(1);
             }
           close(fd[0]); /* not needed after dup2 */
         }
           
       execlp ("sort", "sort", "-n", "+5", (char *) 0);
       printf ("First child finished\n");
     } 
   else 
     { /* processing for parent */
       printf ("The parent process continues.\n");

       /* spawn second process */
       if ((pid2 = fork()) < 0)  /* apply fork again for second child*/
         { perror ("error in fork");  
           exit (1);
         }

       if (0 == pid2)             
        { /* processing for child */
          printf ("The second child process is active.\n");
          close (fd[0]);       /* close input end, leaving output open */
          /* set standard output to pipe */
          if (fd[1] !=  STDOUT_FILENO) 
            { if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
                { perror("dup2 error for standard output");
                  exit(1);
                }
             close(fd[1]); /* not needed after dup2 */
            }

         execlp("cat", "cat", "/home/walker/151s/labs/ia-senate", (char *) 0);
                              /* print to the pipe, now standard output */
        }
       else
        { /* processing continues for parent */
          printf ("Parent closing its pipe ends: parent does not use pipe\n");
          close(fd[0]);
          close(fd[1]);
          printf ("Parent waits for both children to finish.\n");
          waitpid (pid1, NULL, 0); /* wait for first child to finish */
          waitpid (pid2, NULL, 0); /* wait for second child to finish */
          printf ("Parent finished.\n");
        }
     }

   exit (0);
}
