/***********************************/
/* Physics 673 - Assignment #7     */ 
/* Due: November 13, 1996          */ 
/* Forking Processes               */
/* Philip Kayal                    */
/***********************************/

/* Filename: pro.c */

/* Include the following C libraries: */
#include 
#include 
#include 
#include 

/* Define constant strings that will be system calls. */

/* This command will search through pkayal's processes   */
/* for any processes with the name "pro.out".            */
/* So make sure that you call the executable "pro.out"!  */
#define PS1 "ps -lu pkayal | grep pro.out"

main()
{

/* Variable declarations */
  int k, x, sign;
  int pid;

  char proc[] = PS1; 

/* Initialization */
  k = 0;
  x = 0;
  pid = 0;

  printf ("\nProgram started OK \n");

/* Fork */
  pid = fork();

/* Error handling */

  if (pid < 0)
    printf ("\nUnexpected pid value.\n");

    else {

    if (pid == 0) {    /*** CHILD ***/
      sleep(1);

/* Have child process show it is running */
      while (k < 4) {
        printf ("\nChild process %d is still running\n\n", getpid() );
        sleep(5);
        k = k + 1;
      }
      printf ("\nChild process terminated on its own\n\n");
    }

    else {    /*** PARENT ***/
      printf ("\nThe parent process has PID %d \n", getpid() );
      printf ("\nParent process has started child with PID %d \n\n",pid);

/* Make system call to list processes.                  */
/* At this point, the parent and child processes        */
/* should both be shown.                                */

      system(proc);

/* Use waitpid to wait for child process to finish */

      sleep(1);

      while (x == 0) {

/* Make system call to list processes.                   */
/* This is done here so that a zombie will be seen when  */
/* child process finishes.                               */

        system(proc);

        if (waitpid(pid,0,WNOHANG) == 0) {
          sleep(5);
        }
        else {
          x = 1;
        }
      }

/* Child process has finished */

      printf("\nParent sees that child process %d has terminated\n\n",pid);

/* Make system call to list processes.                     */
/* At this point, only the parent process should be shown. */

      system(proc);

      sleep(5);
   
      printf ("\nParent terminates\n");

      printf ("\nProgram finished OK \n");
    }

  }
  return;
}