Home Linux Program to create an orphan process

Program to create an orphan process

by Anup Maurya
13 minutes read

In this article, you’ll learn about what is orphan process and create an orphan process using C Programming.

What is Orphan Process?

A process whose parent process no more exists i.e. either finished or terminated without waiting for its child process to terminate is called an orphan process.

Suppose P1 and P2 are two process such that P1 is the parent process and P2 is the child process of P1. Now, if P1 finishes before P2 finishes, then P2 becomes an orphan process.

In the following code, parent finishes execution and exits while the child process is still executing and is called an orphan process now.

However, the orphan process is soon adopted by init process, once its parent process dies.

Program to create an orphan process

#include<stdio.h
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t p;
p=fork();
     if(p==0)
     {
         sleep(5); //child goes to sleep and in the mean time parent terminates
         printf("I am child having PID %d\n",getpid());
         printf("My parent PID is %d\n",getppid());
     }
     else
     {
         printf("I am parent having PID %d\n",getpid());
         printf("My child PID is %d\n",p);
     }
 }

How it Works?

In this code, we add sleep(5) in the child section. This line of code makes the child process go to sleep for 5 seconds and the parent starts executing. Since, parent process has just two lines to print, which it does well within 5 seconds and it terminates. After 5 seconds when the child process wakes up, its parent has already terminated and hence the child becomes an orphan process. Hence, it prints the PID of its parent as 1 (1 means the init process has been made its parent now) and not 138.

Note: The process will not return to the command prompt. Hence, use Ctrl+C to come to the command prompt.

Practice Programs on Program to create an orphan process

Q1. Create two child process C1 and C2. Make sure that only C2 becomes an orphan process.

Viva Questions on Program to create an orphan process

Q1. What is an orphan process?
Q2. What is the importance of using sleep() function in the above code?
Q3. Why the program didn’t return the command prompt even after termination?

related posts

Leave a Comment