Create zombie process

user3354832 picture user3354832 · Aug 7, 2014 · Viewed 19.8k times · Source

I am interested in creating a zombie process. To my understanding, zombie process happens when the parent process exits before the children process. However, I tried to recreate the zombie process using the following code:

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

int main ()
{
  pid_t child_pid;

  child_pid = fork ();
  if (child_pid > 0) {
    exit(0);
  }
  else {
    sleep(100);
    exit (0);
  }
  return 0;
}

However, this code exits right after execute which is expected. However, as I do

ps aux | grep a.out

I found a.out is just running as a normal process, rather than a zombie process as I expected.

The OS I am using is ubuntu 14.04 64 bit

Answer

chrk picture chrk · Aug 10, 2014

Quoting:

To my understanding, zombie process happens when the parent process exits before the children process.

This is wrong. According to man 2 wait (see NOTES) :

A child that terminates, but has not been waited for becomes a "zombie".

So, if you want to create a zombie process, after the fork(2), the child-process should exit(), and the parent-process should sleep() before exiting, giving you time to observe the output of ps(1).

For instance, you can use the code below instead of yours, and use ps(1) while sleep()ing:

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

int main(void)
{
    pid_t pid;
    int status;

    if ((pid = fork()) < 0) {
        perror("fork");
        exit(1);
    }

    /* Child */
    if (pid == 0)
        exit(0);

    /* Parent
     * Gives you time to observe the zombie using ps(1) ... */
    sleep(100);

    /* ... and after that, parent wait(2)s its child's
     * exit status, and prints a relevant message. */
    pid = wait(&status);
    if (WIFEXITED(status))
        fprintf(stderr, "\n\t[%d]\tProcess %d exited with status %d.\n",
                (int) getpid(), pid, WEXITSTATUS(status));

    return 0;
}