#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>


int fork_child(int sleeptime);

/* Handler to reap zombies */
void handler_sigchld(int sig) 
{
  pid_t pid;
  int status;

  pid = wait(&status);
  if (pid == -1) {
    perror("wait()");
  } else {
    fprintf(stdout,"Slaying zombie %d (which exited with code %d)\n",
          pid, WEXITSTATUS(status));
  }
  return;
}

int main(int argc, char **argv)
{
  int i;

  signal(SIGCHLD,handler_sigchld);

  /* Create 10 children that sleep a random number 
   * of seconds before exiting */
  for (i=0; i < 10; i++) {
    if (fork_child(rand() % 50) == -1) {
      exit(1);
    }
  }

  unsigned int tosleep = 50;

  /* sleeping while being resilient to children notifications */
  while (tosleep > 0) {
    fprintf(stdout,"Sleeping for %d seconds\n",tosleep);
    tosleep = sleep(tosleep);
  }
  fprintf(stderr,"Done sleeping\n");
  exit(0);
}

int fork_child(int sleeptime)
{
  pid_t pid;

  pid = fork();

  if (pid < 0) {
    fprintf(stderr,"Error: can't fork a process\n");
    perror("fork()");
    return -1;
  } else if (pid == 0) { // I am the child
    sleep(sleeptime);
    exit(sleeptime);
  }
  return 0;
}

