/* zombie.c - Program to demonstrate how zombies may occur.

   We have two parts. 
   In the first part the program forks and then waits for input.
   The child just announces its presence and dies.
   The child will be a zombie from its death until the parent 
   responds to the prompt and executes a wait.
   In the second part the parent indicates that it will ignore
   the SIGCHLD signal and then forks just like before. 
   I had read that in this case there would be no zombie.
   But as you can see (on my OSF1 V4.0), a zombie is created.
   You can see info about your processes at the shell prompt with
      % ps aux | grep $USER
 */

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

int
main()
{
  pid_t pid, self;
  char line[256];
  int status;

  printf("\nPart One\n\n");
  if ( (pid = fork()) < 0) {
    perror("cannot fork");
    exit(1);
  }
  if (pid == 0) { // the child
    self = getpid();
    printf("%d I am the child, now check and see I am a zombie\n", self);
    return;
  }
  // the parent
  self = getpid();
  printf("%d Enter a string: ", self);
  scanf("%s", line);
  wait(&status);
  printf("%d Now the zombie is gone\n", self);

  printf("\nReady to continue? ");
  scanf("%s", line);
  printf("\nPart Two\n\n");
  signal(SIGCHLD, SIG_IGN);
  if ( (pid = fork()) < 0) {
    perror("cannot fork");
    exit(1);
  }
  if (pid == 0) { // the child
    self = getpid();
    printf("%d I am the child, now check and see if I am a zombie\n", self);
    return;
  }
  // the parent
  printf("%d Enter a string: ", self);
  scanf("%s", line);

  return 0;
}
