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

Prerequisite: Zombie and Orphan Processes in C

Zombie Process:
A zombie process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the parent process to read its child’s exit status.
A process that terminates cannot leave the system until its parent accepts its return code. If its parent process is already dead, it’ll already have been adopted by the “init” process, which always accepts its children’s return codes. However, if a process’s parent is alive but never executes a wait ( ), the process’s return code will never be accepted and the process will remain a zombie.

Orphan Process:
An orphan process is a process that is still executing, but whose parent has died. They do not become zombie processes; instead, they are adopted by init (process ID 1), which waits on its children.
When a parent dies before its child, the child is automatically adopted by the original “init” process whose PID is 1.

Approach:
In the following code, we have made a scenario that there is a parent and it has a child and that child also has a child, firstly if our process gets into child process, we put our system into sleep for 5 sec so that we could finish up the parent process so that its child become orphan, then we have made a child’s child as zombie process, the child’s child finishes its execution while the parent(i.e child) sleeps for 1 seconds, hence the child’s child doesn’t call terminate, and it’s entry still exists in the process table.

Below is the implementation of above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to execute zombie and
// orphan process in a single program
#include <stdio.h>
int main()
{
  
    int x;
    x = fork();
  
    if (x > 0)
        printf("IN PARENT PROCESS\nMY PROCESS ID 
                              : %d\n", getpid());
  
    else if (x == 0) {
        sleep(5);
        x = fork();
  
        if (x > 0) {
   printf("IN CHILD PROCESS\nMY PROCESS ID :%d\n
           PARENT PROCESS ID : %d\n", getpid(), getppid());
  
   while(1)
     sleep(1);
  
   printf("IN CHILD PROCESS\nMY PARENT PROCESS ID 
                               : %d\n", getppid());
        }
  
        else if (x == 0)
            printf("IN CHILD'S CHILD PROCESS\n
                  MY PARENT ID : %d\n", getppid());
    }
  
    return 0;
}

chevron_right


Output:

Note: Above code may not work with the online compiler as fork() is disabled.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.