C program for Parent process registering for SIGCHLD signal and waits in the signal handler for Child process to die

C program for Parent process registering for SIGCHLD signal and waits in the signal handler for Child process to die

  
#include <stdio.h>

#include <signal.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/wait.h>

#include <stdlib.h>

void handler(int sig)

{

  pid_t pid;

  pid = wait(NULL);

  printf("Pid %d exited. Signal caught\n", pid);

}

int main(void)

{

  signal(SIGCHLD, handler);

  if(!fork())
  {
    printf("\n Child pid is %d\n", getpid());

    printf("\n child exited\n");

    exit(0);
  }

  printf("Parent pid is %d\n", getpid());
  getchar();

  return 0;
}

Output:
Parent pid is 2249
Child pid is 2250
child exited
Pid 2250 exited. Signal caught