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


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)
{
  pid_t pid;

  pid = fork();

  if (pid < 0) {
    fprintf(stderr,"Error: can't fork a process\n");
    perror("fork()");
    exit(1);
  } else if (pid) { // I am the parent
    unsigned int tosleep;

    signal(SIGCHLD,handler_sigchld);
    fprintf(stdout,"I am the parent and I am sleeping for 100 seconds\n");
    // Yes, you should check the return value of sleep!!!
    tosleep = sleep(100);
    fprintf(stdout,"I am the parent and I slept %d seconds\n",100-tosleep);
    exit(0);
    
  } else {  // I am the child and I exit after sleeping 4 seconds
    sleep(4);
    exit(42);
  }
}

