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.
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.
The following code example describes this concept:
pid = fork();
if (pid == 0)
printf(“This is a child process and pid is %dn”, getpid());
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.