If you have worked with Linux processes there is a high chance that you have seen these terms, zombie process and orphan process. They can be confusing sometimes, in this article we are going to look at the difference between an orphan process and a zombie process with help of some C coding.
What is a process?
Process in an operating system is a program in execution. Information about the process is stored in the Process Control Block (PCB). An entry of PCB is added to the process table which is nothing but an array of PCBs. Processes have a parent-child relationship.
An orphan process is one when the parent dies or finishes execution before the child process exits. It’s the parent process’s responsibility to terminate the child process and remove entries from the process table. Let’s have a look at how the orphan process is created and what happens when the parent process dies.
As we can observe, the child is executing an infinite while loop and printing the parent’s
PID. Whereas, the parent process completes execution without terminating the child process.
So, when the parent process dies while the child process is still in execution. The process with
PID 1 adopts it which is init or Systemd based on the distro used.
When the child process finishes execution
SIGCHLD signal is delivered to the parent process by the kernel. The parent process reads the child’s status from the process table and then removes the entry. Let’s see some proof:-
In the above code, we can observe that we have written a custom handler for the
SIGCHLD signal. This means whenever the
SIGCHLD signal generates. Our custom handler would execute to print `
Don't Worry! Handler is here!!!!
wait() system call ensures the parent doesn’t exit or sit idle till the child process completes.
This proves when the child process exits, a
SIGCHLD signal is sent to the parent process.
A process becomes a Zombie process when it has terminated but its entry is still there in the process table. When a process completes its execution. Its entry from the process table should be removed by the parent process. When the parent process doesn’t wait for the completion of the child process. It leads to the creation of a zombie process. Let’s have a look at how the zombie process created
In the above code, the child process spawns and finishes execution. While the parent process is executing sleep. The child process’s entry would remain in the process table and it continues to exist in the Zombie state. Until the parent process could wake up and terminate the child process.
Thus it is important to handle these cases as a lot of zombie processes would occupy the whole memory.
I pushed the above code in my github repo. Drop a star if you think it is helpful 🙂 Try for yourself and you could do some experimentation as well.
If you like the article, please share and subscribe to the blog.