/*                 Physics 673 Assignment Number 7                   */
/*                 Bryan L. Caron  November 11, 1996                 */
/*                                                                   */
/* In this program a child process is forked and susequently sleeps  */
/* 20 seconds.  During this time the parent checks for the existence */
/* of the child process and does not teriminate until the child has  */
/* first terminated.                                                 */

#include      /* header file for standard i/o               */
#include  /* header file for fork(), waitpid() commands */
#include     /* header file for fork() command             */
#include   /* header file for waitpid() command          */

main()
{

int i;
int j;
int k;
int status;

/* Print current process id value */

printf( "Pre-fork Process ID:%d\n", getpid() );
printf( "Pre-fork Parent Process ID:%d\n",getppid() );

printf( "\n Fork a new process ...\n" );

/* flush stdout stream and fork a new process */

fflush( stdout );

i = fork();

if( i <0 ) {
  printf( "Return code = %d Fork failed. Clean up and exit.\n", i );
}
else { 
  if( i == 0 ) {
    printf( "\n\t fork() return value = %d\n",i );
    printf( "\t This process is a Child with Process ID:%d\n", getpid() );
    printf( "\t Child's Parent Process ID:%d\n",getppid() );

    sleep(20);
  }
  else {
    printf( "\n\t fork return value =  %d\n",i );
    printf( "\t This process is a Parent with Process ID:%d\n\n", getpid() );

    system( "ps" );

    printf( "\n\t Waiting for Child to finish " );

/* Set options = 1: This lets the parent process continue */

/* while loop statements occur for whenever j is 0 (child still running) */

    while ( ! (j = waitpid ( i , &status , 1 )) ) {
      fflush(stdout);
      printf( "." );
      sleep(1);
}

    printf( "\n\n waitpid() return value = %d\n\n",  status );

    system( "ps" );

    printf( "\n Child Process ID %d has terminated.", j );
    printf( "\n Parent Process ID %d now terminates.\n", getpid() ); 
  }
}

}