In: Computer Science
Write a C program to create a series of processes, as shown below in the diagram.
P - ------------------ > c1 ------------>c3
| |
|------------------> c2 |----- >c4
In other words, the parent process p creates processes c1 and c2, c1 creates c3 and c4.
We use the fork() call, which returns a value of type pid_t. The distinguishing factor is :
Following is the code in multiple_forks.c :
#include <unistd.h>
#include <stdio.h>
int main()
{
/*
* P
*/
printf("P : [0x%x]\n", getpid());
{
pid_t pid = fork();
if(pid == 0)
{
/*
* Context: c1
*/
printf("c1 : [0x%x], c1's parent : [0x%x]\n",
getpid(), getppid());
{
pid_t pid = fork();
if(pid == 0)
{
/*
* Context: c3
*/
printf("c3 : [0x%x], c3's parent : [0x%x]\n",
getpid(), getppid());
}
else
{
/*
* Context c1
*/
{
pid_t pid = fork();
if(pid == 0)
{
/*
* Context: c4
*/
printf("c4 : [0x%x], c4's parent : [0x%x]\n",
getpid(), getppid());
}
}
}
}
}
else
{
/*
* Context: P
*/
{
pid_t pid = fork();
if(pid == 0)
{
/*
* Context: c2
*/
printf("c2 : [0x%x], c2's parent : [0x%x]\n",
getpid(), getppid());
}
}
}
}
/*
* Loop indefinitely, so that no process dies.
*/
while(1)
{
sleep(1000);
}
return 0;
}
Following is the compilation step :
gcc multiple_forks.c -o multiple_forks
Following is a sample run :
./multiple_forks
P : [0x1e6a]
c1 : [0x1e6b], c1's parent : [0x1e6a]
c2 : [0x1e6c], c2's parent : [0x1e6a]
c3 : [0x1e6d], c3's parent : [0x1e6b]
c4 : [0x1e6e], c4's parent : [0x1e6b]
As seen,
We see the same pattern across multiple runs, as follows :
./multiple_forks
P : [0x1e82]
c2 : [0x1e84], c2's parent : [0x1e82]
c1 : [0x1e83], c1's parent : [0x1e82]
c3 : [0x1e85], c3's parent : [0x1e83]
c4 : [0x1e86], c4's parent : [0x1e83]
./multiple_forks
P : [0x1e87]
c1 : [0x1e88], c1's parent : [0x1e87]
c2 : [0x1e89], c2's parent : [0x1e87]
c3 : [0x1e8a], c3's parent : [0x1e88]
c4 : [0x1e8b], c4's parent : [0x1e88]
./multiple_forks
P : [0x1e8c]
c1 : [0x1e8d], c1's parent : [0x1e8c]
c2 : [0x1e8e], c2's parent : [0x1e8c]
c3 : [0x1e8f], c3's parent : [0x1e8d]
c4 : [0x1e90], c4's parent : [0x1e8d]