In: Computer Science
Write a C program to create a series of processes, as shown below in the diagram.
P |------ ---- > c1 |------------>c2
|------- ------>c3 ---------->c4
In other words, the parent process p creates process c1, c1 creates c2 and c3, and c3 creates c4.
A sample run of the program shows
Your program should output something similar to what is shown above. You could optionally use wait/waitpid/sleep/exit in your program.
Comment your code to show where you created p, c1, c2, c3, c4, etc.
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: c2
*/
printf("c2 : [0x%x], c2's parent : [0x%x]\n",
getpid(), getppid());
}
else
{
/*
* Context c1
*/
{
pid_t pid = fork();
if(pid == 0)
{
/*
* Context: c3
*/
printf("c3 : [0x%x], c3's parent : [0x%x]\n",
getpid(), getppid());
{
pid_t pid = fork();
if(pid == 0)
{
/*
* Context: c4
*/
printf("c4 : [0x%x], c4's parent : [0x%x]\n",
getpid(), getppid());
}
}
}
}
}
}
}
}
/*
* Loop idefinitely, so that no process dies.
*/
while(1)
{
sleep(1000);
}
return 0;
}
Following is a sample run :
./multiple_forks
P : [0x1f10]
c1 : [0x1f11], c1's parent : [0x1f10]
c2 : [0x1f12], c2's parent : [0x1f11]
c3 : [0x1f13], c3's parent : [0x1f11]
c4 : [0x1f14], c4's parent : [0x1f13]
As seen,