#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

int procCtr;

void sigReceived(int sigNo)
{
  procCtr--;
  printf("Receiving signal %d, decreasing procCtr!  Value now=%d\n", sigNo, procCtr);
  return;
}

pid_t makeBaby(int sleeptime, int myId)
{
  pid_t p;

  p = fork();
  if (p < 0)
    {
      fprintf(stderr, "Ooops, pid got negative!\n");
      fflush(stderr);
      exit(1);
    }
  if (p>0)
    {
      procCtr++;
      return p;
    }
  else
    sleep(sleeptime);
  fprintf(stdout, "Baby %d will exit now!\n", myId);
  fflush(stdout);
  _exit(0);
}

int main(int argc, char *argv[])
{
  pid_t c1, c2, c3;
  
  procCtr = 0;
  signal(SIGCHLD, sigReceived);
  c1 = makeBaby(5, 1);
  c2 = makeBaby(10, 2);
  c3 = makeBaby(15, 3);
  while (procCtr > 0)
    {
      sleep(2);
      printf("Mainmother woke up! Proc-counter is %d\n", procCtr);
    } 
  return 0;
}
