News

Process synchronisation in Linux

The two fundamental concepts in a Linux operating system are processes and time slice. A process is an instance of a program that is being executed by the computer’s operating system. When we say that two computers are communicating with each other, we mean that two processes, one running on

Orphan process code example
In this example (Fig 8 above), we first create a child process by invoking the fork() call. If the ‘if’ condition becomes true (that is, child process getting the time slice first), then two printf statements will display the child’s PID as well as its parent’s PID. Now we have a sleep call that puts the child process to sleep for 20 seconds (ie. it will be inactive for that time). In the meantime, the parent process will get the time slice and the two printf statements in the parent process will be executed, thereby printing the parent’s process PID as well as its parent’s PID. As expected, after printing the PIDs, the parent process will terminate. Now we have a parentless child process. Once its sleep is over, the next two printf statements (in the parentless child process) are executed. And two PIDs will be displayed. We need to note here that when the child becomes parentless, its parent’s PID will be 1 (Fig 9 below) – this is the result of a process called ‘process dispatcher’ and it is this that adopts an orphan process.
Orphan process - output displayWhen we have multiple processes, we need to have a mechanism to provide synchronisation between the processes. The sleep() system call is used for this purpose. We have seen above how sleep can be introduced in a specific process for a specific purpose. We normally encounter another situation where the child process terminates before the parent process. Here the child is still consuming system resources but not executing. Such a process is referred to as a zombie process.

Consider the following code example:

#include<stdio.h>
main()
{
if ( fork() > 0)
{
printf(“This is a parent processn”);
sleep (20);
}
}

In the above example, the fork() creates a child process. Here, the child is nothing but a duplicate of the parent process. Execution of both processes starts from the line after the fork() call. In this case that line is an ‘if’ condition and we check to see if the value returned by the fork() is greater than 0. Since this condition is not valid for a child process, the child process terminates. The following snapshot (Fig 10 below) displays the output of the above program.
Zombie process - output display
When we execute the ‘ps –el’ command at the command prompt, we basically get a listing of all processes running on a system. The second column shows the status of a process.

×