/* This program creates a child which sleeps for 20 seconds before exiting.
   The messages printed by the child are indented by a tab. The messages
   printed by each process begins with its process id (PID).
   Use "gcc fork.c" to compile this program.
   Type "./a.out" to run the program

   UNDERSTAND THIS PROGRAM COMPLETELY BEFORE WORKING ON THE FIRST ASSIGNMENT.
*/

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

int main(int argc, char **argv) {
    int result, waitPID;

    printf("[%d] parent process\n", getpid());

    if ((result=fork()) == 0) {
                     /* child code */
       printf("\t[%d] child process\n", getpid());
      /* the child can do whatever it wants here, including "exec"
           but this guy just sleeps for 20 seconds */
       sleep(20);
       printf("\t[%d] child awakened\n", getpid());
       exit(1);
      /* child code over */
    } else if (result < 0) {
       perror("fork");                /* fork failed */
    }
/* parent continues here */
    printf("[%d] created the child process with ID = %d\n", getpid(), result);
    printf("[%d] waiting for child to complete\n", getpid());
    waitPID = wait(NULL); /* wait for a child to complete */
    printf("[%d] child with PID %d completed\n", getpid(), waitPID);
}
