/* This program creates a new process and provides a simple pipe to
   allow the parent to communicate with the child 
   Version 2 -- explicitly using pipe, read/write for integers, and wait */

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

int data_g = 4;           /* global data element */

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 pid;

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

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

   if (0 == pid)             
     { /* processing for child */
       printf ("The child process is active.\n");
       close (fd[1]);       /* close output end, leaving input open */
       read (fd[0], &value1, 4);  /* read integer as 4 bytes */
       printf ("The value read from the parent is %d\n", value1);
       printf ("Final data elements in child: global = %d   local = %d\n",
               data_g, data_l);
       printf ("Child finished\n");
     } 
   else 
     { /* processing for parent */
       printf ("The parent process continues.\n");
       data_g = 10;         /* change data elements */
       data_l = 12;
       value = 20;

       printf ("New data elements in parent: global = %d   local = %d\n",
               data_g, data_l);
       close (fd[0]);       /* close input end, leaving output open */
       write (fd[1], &value, 4); /* print value, which uses 4 bytes */
       waitpid (pid, NULL, 0);   /* suspend processing until child finish */
       printf ("Parent finished\n");
     }

   exit (0);
}
