Anand Karandikar
Anand Karandikar

Reputation: 49

linux fork system call

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:

  1. fork()

  2. fork()
    fork()

  3. 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.

Upvotes: 5

Views: 507

Answers (4)

alexgirao
alexgirao

Reputation: 895

extending on @Duck idea, you can do a simple experiment on the command line

perl -le'fork; fork; fork; print $$'  # $$ is the pid

which should yield something like

6792
6795
6796
6797
6798
6799
6800
6801

confirming, that, indeed, three forks create 2^3-1 processes

Upvotes: 0

Tom Pace
Tom Pace

Reputation: 2387

The following link is another stack overflow Q-A about this subject, may help clear things for You.

Problem forking fork() multiple processes Unix

That person Has 5 calls to fork() and ends up spawning 31 new processes. (2^forks-1 original process)

Upvotes: 0

Duck
Duck

Reputation: 27542

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.

Upvotes: 6

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

The third one:

fork()
fork()
fork()

After the first fork, you have 2 processes. So the second fork is called by 2 processes. So, you have 4 processes after the second fork(). The third fork is called by all 4 processes, creating 4 more processes. So, you have 8 processes in total, where 7 processes are created.

Thus, for n forks, there will be a total of 2^n processes, where 2^n-1 processes are created due to the forks.

Upvotes: 3

Related Questions