In this section, we will see how to execute zombie and orphan processes in a single program in C/C. Before getting to the point, let's first understand what zombie processes and orphan processes are.
Zombie process refers to a process that has completed execution but still has remaining space. Entry in the process table. Zombie processes usually occur in child processes because the parent process still needs to read the exit status of its child process. Once this is done using the wait system call, the zombie process is eliminated from the process table. This is called harvesting zombie processes.
Orphaned processes are those processes that are still running even though their parent process has terminated or completed. A process may become orphaned intentionally or unintentionally.
Intentionally orphaned processes will run in the background without any manual support. This is typically done to start a service that runs indefinitely or to complete a long-running job without the user noticing.
Orphaned processes are inadvertently created when their parent process crashes or terminates. Use the process group mechanism to avoid unintentional orphan processes.
Now in the following code we will execute zombie process and orphan process at the same time. Here we have a parent process, which has a child process, and this child process has another child process. If our control is inserted into a child process, then we will stop execution for 5 seconds so that it can complete the parent process. Therefore the child process becomes an orphan process. The grandchild process will then be converted into a zombie process. The grandchild process completes execution when its parent process (a child of the main process) sleeps for 1 second. Therefore, the grandchild process will not call terminate and its entry will exist in the process table.
#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</p><p>", 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</p><p>", getpid(), getppid()); while(1) sleep(1); printf("Inside Child---- PID of parent : %d</p><p>", getppid()); }else if (x == 0) printf("Inside grandchild process---- PID of parent : %d</p><p>", getppid()); } return 0; }
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:~$
The above is the detailed content of How to execute zombie and orphan processes in a single C program?. For more information, please follow other related articles on the PHP Chinese website!