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

int main (int argc, char *argv[])
{
  int status;
  pid_t pid;
  time_t time_started, time_finished;

  int i, num_children;

  if (argc == 2) {
    num_children = atoi (argv[1]);
  } else {
    printf ("Usage: fork2 number_of_children\n");
    exit (-1);
  }

  time (&time_started);

  for (i=0; i<num_children; i++) {
    pid = fork ();

    /* check for an error */
    if (pid == -1) {
      fprintf (stderr, "Fork failed.\n");
      exit (-1);
    }

    /* see if we're the parent or the child */
    if (pid == 0) {
      /* printf ("Hello from child %d.\n", i); */
      exit (i);
    }

    /* parent continues */
    /* printf ("Hello from the parent.\n"); */

    pid = wait (&status);

    if (pid == -1) {
      fprintf (stderr, "Wait failed.\n");
      exit (-1);
    }

    status = WEXITSTATUS(status);
    /* printf ("Oh my god, they killed child %d.  You bastards!\n", status); */
  }

  time (&time_finished);

  /* printf ("%d\n", time_finished-time_started); */

  exit (0);
}


/* HERE'S THE OUTPUT:


*/
