I'm a newbie at unix shell programming and I have a really hard time getting an good explanation about forks and their trees. All I know for now is that a fork kind of copies a process (child) from the main one (parent).
More specifically I can't quite get from a piece of code how a process tree would be like.
For example, at this backbone of code:
pid1=fork();
if (pid1!=0)
{
pid2=fork();
pid3=fork();
}
else
{
pid4=fork();
}
It seems to me that there are 3 processes under the original process (pid1, pid2, pid3) and a child of one of these three (pid4), maybe pid2's.
I tried to run it with some more awfully written code:
int pid1, pid2, pid4, pid4;
printf("I'm the original Process %d with parent %d \n", getpid(), getppid());
pid1=fork();
if(pid1!=0)
{
pid2=fork();
printf("I'm P2 %d with parent %d \n", getpid(), getppid());
sleep(1);
pid3=fork();
printf("I'm P3 %d with parent %d \n", getpid(), getppid());
sleep(1);
}
else
{
pid4=fork();
printf("I'm P4 %d with parent %d \n", getpid(), getppid());
sleep(1);
}
Edit: I put some sleep(1) at the code above, thanks to dbush, so I can see the ppid's
So, how is the tree forming with these types of code?