Fork question

A question asks how many processes are created at the end of the loop below.

1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <unistd.h>
int main()
{
    int i;
    for (i = 0; i < 4; i++)
        fork();
    return 0;
} 


I counted 16, but the answer is 8 apparently. Might the solution's answer be wrong? I don't see how it is 8 considering you have 8 processes by the 3rd iteration, and since 3<4, you fork once more and you get 16 processes and by then 4==4 so you exit the for loop.
Last edited on
1
2
3
4
    for (i = 0; i < 4; i++){
        fork();
        std::cout << getpid() << '\n';
}
$ ./a.out | sort | uniq | wc -l
16
Last edited on
you have 8 processes by the 3rd iteration

You have 8 processes after the iteration where i = 3 (which is the 4th and final iteration).

i = 0: 1 process and fork to 2
i = 1: 2 processes , fork to 4
i = 2: 4 processes , fork to 8
i = 3: 8 processes , fork to 16
i = 4: 16 processes, don't enter the loop
I actually misread the solution. I was looking at a solution to a different problem, my bad. Yes it has to be 16.
Topic archived. No new replies allowed.