/* include header files */

#include <stdio.h>       // printf
#include <stdlib.h>      // exit
#include <unistd.h>      // sleep, getpid, fork
#include <sys/types.h>   // getpid, fork, wait
#include <sys/wait.h>    // wait

/* define section */

#define MAX_CHILDREN 5

/* main function */

int main(){          
  
  int child_pid,i;
  
  for (i=1;i<MAX_CHILDREN;i++) {

    child_pid = fork();

    if (child_pid == 0) {
      
      /* child section */
      
      printf("Child %d: ready\n",getpid());
      sleep((getpid()%3)*3); 
      printf("Child %d: completed\n",getpid());
      
      exit(0);
    }
    
    /* parent section */
    
    printf("Parent: child %d created\n",child_pid);
  }
  
  /* parent section */
  
  printf("Parent: waiting for children to exit\n");
  
  for(i=1; i < MAX_CHILDREN; i++) {

    child_pid=wait(NULL);
    
    printf("Parent: child %d completed\n",child_pid);    
  }
  
  printf("Parent: End\n");

  return 0;
}

