简体   繁体   中英

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.

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 pgm | sort | uniq

9314
9317
9318
9319
9320
9321
9322
9323

8 total processes, seven created ones.

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.

The following link is another stack overflow QA 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM