Recently I faced an technical interview in a reputed IT firm. the interviewer asked me about how many processes will be created if the following 3 different fork system call invocations are given:
fork()
fork()
fork()fork()
fork()
fork()
The answer to first was obvious 2 processes.
2nd one will start 3 processes.
bt the 3rd I told was 5 processes, the interviewer disagreed and said its 7.
I cannot figure out how did it create 7 processes.
Please help.
You need to nail the interviewer down on whether it is total processes or created processes. This is a simple technique (in most of these fork
puzzles) on a posix system.
int main(int argc, char *argv[])
{
fork();
printf("%d\n", getpid());
fork();
printf("%d\n", getpid());
fork();
printf("%d\n", getpid());
return(0);
}
And then just run it as: pgm | sort | uniq
9314
9317
9318
9319
9320
9321
9322
9323
8 total processes, seven created ones.