/**/ What is a Zombie Process? - Dextutor - Programs

What is a Zombie Process?

A zombie is a process which has terminated but its entry still exists in the process table until the parent terminates normally or calls wait(). Suppose you create a child process and the child finishes before the parent process does. If you run the ps command before the parent gets terminated the output of ps will show the entry of a zombie process(denoted by defunct ). This happens because the child is no longer active but its exit code needs to be stored in case the parent subsequently calls wait.

Program



//zombie.c
#include<stdio.h>
#include<unistd.h>
int main()
{
   pid_t t;
   t=fork();
   if(t==0)
   {
       printf("Child having id %d\n",getpid());
    }
    else
    {
        printf("Parent having id %d\n",getpid());
        sleep(15); // Parent sleeps. Run the ps command during this time
    }
}

Output:

$gcc zombie.c

$./a.out &

what is a zombie process ?

How it works?

Now Compile the program and run it using ./a.out &. The ‘&’ sign makes it run in the background. After you see the output of both the printf statement, note that the parent will go into sleep for 15 seconds. During this time type the command ‘ps’. The output will contain a process with defunct written in the end. Hence, this is the child process (can be verified from PID) which has become zombie.

How to prevent the creation of a Zombie Process?

In order to prevent this use the wait() system call in the parent process. The wait() system call makes the parent process wait for the child process to change state. Click here for more details

Video Link

Practice Program on Zombie Process

Q. Create a scenario where a parent has two child process C1 and C2 such that C1 becomes a zombie while C2 becomes an orphan process.

Viva Questions on Zombie Process

Q1. How can you identify the existence of a zombieprocess in the system?
Q2. What is the importance of using sleep() function in the above code?

Other Relevant Programs

Program to create an Orphan Process
Program to duplicate a process using fork() system call
Understanding the execl() system call
Program to create threads in Linux
open() system call

Leave a Comment