How to execute zombie and orphan process in a single C program?


In this section we will see how to execute zombie process and orphan process in a single program in C/C++. Before going to the main discussion, let us see what are the zombie process and orphan process.

Zombie Processes

A zombie process is a process whose execution is completed but it still has an entry in the process table. Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit status. Once this is done using the wait system call, the zombie process is eliminated from the process table. This is known as reaping the zombie process.

Orphan Processes

Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally.

An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention.

An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism.

Now in the following code we will execute zombie and orphan process simultaneously. Here we have a parent process, it has a child, and this child has another child. If our control inserts into child process, then we will stop the execution for 5 seconds so it can finish up the parent process. Thus the child process become orphan process. After that the grandchild process will be converted into Zombie process. The grandchild finishes execution when its parent (the child of the main process) sleeps for 1 second. Hence the grandchild process does not call terminate, and its entry will be there in the process table.

Example Code

#include <stdio.h>
#include <unistd.h>
int main() {
   int x = fork(); //create child process
   if (x > 0) //if x is non zero, then it is parent process
      printf("Inside Parent---- PID is : %d
", getpid());    else if (x == 0) { //for chile process x will be 0       sleep(5); //wait for some times       x = fork();       if (x > 0) {          printf("Inside Child---- PID :%d and PID of parent : %d
", getpid(), getppid());          while(1)             sleep(1);          printf("Inside Child---- PID of parent : %d
", getppid());       }else if (x == 0)       printf("Inside grandchild process---- PID of parent : %d
", getppid());    }    return 0; }

Output

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Inside Parent---- PID is : 3821
soumyadeep@soumyadeep-VirtualBox:~$ Inside Child---- PID :3822 and PID of parent : 686
Inside grandchild process---- PID of parent : 3822
soumyadeep@soumyadeep-VirtualBox:~$

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements