Trace is as follows:
Code:
i = 0;
parent forks()....
We now have 2 processes. 1 parent and 1 child
i = 1;
parent forks()....
We now have 3 processes. 1 parent and 2 children
child forks()....
We now have 4 processes. 1 parent and 2 children and 1 grandchild
i = 2;
Loop ends.
Total processes: 4
I wrote the following bad code really quickly:
Code:
#include <stdio.h>
#include <wait.h>
int main()
{
int i, iReturn;
pid_t pid;
for(i=0;i<2;i++)
{
pid = fork();
printf("%d reporting for duty\n",getpid());
if(pid > 0)
{
pid = wait(&iReturn);
}
}
return 0;
}
Output:
Code:
17244 reporting for duty
17245 reporting for duty
17245 reporting for duty
17246 reporting for duty
17244 reporting for duty
17247 reporting for duty
Now you'll get 6 entries, but notice the identical PID's? That's because you're in a loop and printing notices multiple times by some of the processes.
Taking out the duplicate entries:
Code:
17244 reporting for duty
17245 reporting for duty
17246 reporting for duty
17247 reporting for duty
Surprise! Only 4 processes.