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

Here, we create a duplicate child process by invoking the fork() call. Execution in both processes starts from fork(). Assume that at this time, the parent process gets the time slice. We have a wait() inside the parent process and thus the latter is suspended. Once the parent process is suspended, it is not reactivated till the variable ‘i’ in the child process becomes 1,000 and the execution ends. After this, a signal is sent to the parent process and the parent process resumes. SIGCHLD is the signal sent to the parent process when the child process terminates.

We normally encounter situations where a parent has created many children and wants to wait till all of them have terminated. One way of doing this is to put the parent to sleep for a certain amount of time. This time will be what it takes for the children to execute before they terminate.

The following example illustrates how to make the parent wait for more than one child:

#include<stdio.h>
main()
{
int pid,dip;
pid = fork();
if (pid == 0)
{
printf(“1st Child’s process id is %dn”, getpid());
printf(“End of 1st Child processn”);
}
else
{
dip = fork();
if(dip == 0)
{
printf(“2nd Child’s process id is %dn”,getpid());
printf(“End of 2nd Child processn”);
}
else
{
sleep(20);
printf(“Parent process is dyingn”);
}
}
}

Here, once we invoke a fork() call, the first child executes and dies. The parent process is activated again and goes onto fork() a second child. Now once again, we will have two processes. Since the parent process has been put to sleep, the child process finishes. Finally, the parent process is given the time slice and it executes its functions and then terminates.

The following snapshot (Fig 13 below) displays the output of the program.

Parent waiting for more than one child

Thus, the wait() system call will tell us in what manner the process was terminated – whether a process got terminated normally or abnormally. For this, we need to pass an integer variable to the wait() call. If a process was terminated normally, then the high-order 8 bits of the integer variable passed to the wait() will be updated while the lower-order 8 bits will be initialised to 0. If a process was terminated abnormally, then the lower-order 8 bits will be updated while the high-order 8 bits will be initialised to 0. Thus, any program that uses the wait() system call can be queried to find out the mode of termination.

×