Featured Post

Trie implementation in C

How to create a Zombie Process

Have you seen the movie 'Resident Evil'? Then you probably know what a Zombie is !
Just like when the people die and still are able to walk and talk , in short way their last rituals were not performed , they become Zombies , the process also which has terminated but has not been cleaned up yet is called a "Zombie" process.

It is the responsibility of the wait function in the parent process to clean up its zombie children.If the child process finishes before the parent process calls wait,the child process becomes a zombie.When the parent process calls wait, the zombie child’s termination status is extracted, the child process is deleted, and the wait call
returns immediately.

And if the parent doesn't do the cleanup the Zombie remains in the system.


The zombie process can be seen using the following command.

"ps -e -o pid,ppid,stat,cmd"

The state for Zombie process in linux/unix is marked as Z+

Here's a simple implementation to create a Zombie Process.
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
  pid_t child_pid;

   /* Create child*/
  child_pid = fork ();
  if (child_pid > 0) {

    /* Parent process */
    sleep (60);
  }
  else {

    /*Child process. Exit immediately. */
    exit (0);
  }
  return 0;
}


Here is a method to avoid the process from becoming Zombie or in better words , cremating the process properly.
The cleanup is done by the signal handler.

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

sig_atomic_t child_exit_status;
void clean_up_child_process (int signal_number)
{
  /* Clean up the child process. */
  int status;
  wait (&status);

  /* Store its exit status in a global variable. */
  child_exit_status = status;
}

int main ()
{
  pid_t child_pid;

  /* Handle SIGCHLD by calling clean_up_child_process. */
  struct sigaction sigchld_action;
  memset (&sigchld_action, 0, sizeof (sigchld_action));
  sigchld_action.sa_handler = &clean_up_child_process;
  sigaction (SIGCHLD, &sigchld_action, NULL);

   /* Create child*/
  child_pid = fork ();
  if (child_pid > 0) {

    /* Parent process */
    sleep (60);
  }
  else {

    /*Child process. Exit immediately. */
    exit (0);
  }
  return 0;
}

Comments

  1. Couldn't run code. Not sure if the struct part works, lots of bugs for me. Also confused on how fork function works, is it part of an include library or does it need to be defined in our own code?

    ReplyDelete

Post a Comment

Please post your valuable suggestions