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

The fork creates a child process that is a duplicate of the parent process. In the above example, the parent process is the program being listed. Since now we have two identical processes in memory, the printf statement will be executed twice. We need to note
here that the child process begins from the fork() statement. That is, all the statements after the call to fork() will be executed twice – once by the parent process and once by the child process.
PID of a process

Every process in the Linux operating system has a process identification number (referred to as process ID or PID) and this will help in differentiating one process from another. The snapshot (Fig 3 above) shows how we can print the PID of a specific process.

We can see (Fig 4 below) that our program has displayed PIDs of both the parent and child processes. There is a need for us to know which is the PID of the parent and which PID is that of the child process. We can use the fork() system call to find this information. In the parent process, the fork() returns the PID of the child process; while in the child process, it returns a value of zero.

PID display

The following code example describes this concept:

#include<stdio.h>
main()
{
int pid;
pid = fork();
if (pid == 0)
printf(“This is a child process and pid is %dn”, getpid());
else
printf(“This is a parent process and pid is %dn”,getpid());
}

In the above example, the return value of the fork() system call is stored in a variable ‘pid’. And then a check is made to see if it is a parent process or a child process.

×