Linux Zombie process, orphan process and daemon process in C

In this chapter we shall see what are Linux Zombie process, orphan process and daemon process.

Linux Zombie Process

* A process that has completed it’s execution but still has an entry in process table is called as Zombie process.

* Ideally zombie process will not harm other process. It will be there in process table. It will not take memory or CPU

* But when there are no other PID available in the system, and the new process cannot use the PID used by zombie process. Hence the new process will not be executed.

* zombie process is also called as defunct process.

* zombie process occurs because, the child is waiting for the parent process to read its exit status.

* zombie process will occur, because parent process did not invoke wait() system call.

#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 
int main() 
{ 
    // Fork returns process id in parent process 
    pid_t child_pid = fork(); 
  
    // Parent process  
    if (child_pid > 0) 
    {
        sleep(70); 
    }
  
    // Child process 
    else 
    {       
        exit(0); 
    }
  
    return 0; 
} 

* In the above program, the child process exit immediately once it is created, and we are not calling the wait() system call.

* The parent process is sleeping for 70 seconds, till that time, the child process id will be preset in process table.

* Hence child will be in zombie state for 70 seconds.

Linux Orphan Process

* A child process whose parent has died is called as an Orphan Process.

* A parent process might have crashed, making the child process to go into orphan state.

* Or a child process is intentionally gets detached from parent process to process a long running task in the background.

* Orphaned children are immediately “adopted” by init.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{

	int pid = fork();
	if (pid > 0)
	{
		printf("\nParent process ID : %d\n\n",getpid());
	}
	else if (pid == 0)
	{
		printf("\nChild process ID: %d\n",getpid());
		printf("\nParent Process ID: %d\n",getppid());

		sleep(10);

		// by this time, parent process has finished execution.
		// and it will be killed.
		// if you see the parent ID, it will be changed.
        // this is orphan process
		printf("\nChild process  ID: %d\n",getpid());
		printf("\nParent process ID: %d\n",getppid());
	}
	return 0;
}

Linux Daemon Process

* Daemon process are intentional Orphan Process.

* They are run in background without associated with any terminal

* Usually long running programs without user input will be made as daemon process.

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *