Skip to content
Advertisement

Fork how many processes created confused

Say i have the following program

pid_t pid = fork();  // fork #1
pid = fork();        // fork #2

So now what we have:

  1. Fork #1 creates an additional processes. so now we have two processes.
  2. Fork #2 is executed by two processes, creating two processes, for a total of four.

My confusion is after the first fork we will have two processes P1(parent) and C1 (child). each process will execute the second fork once. so shouldn’t we have 6 processes since P1 will create two more and C1 also? or is it that only the P1 can execute the second fork creating P2 C2

Advertisement

Answer

A good general rule is that one process calls fork but two return from it (assuming it works, of course).

Both returning processes continue executing after the return from the fork, something I suspect you man not have fully understood based on your confusion.

That means you go from one process to two in the first fork, then each of those processes calls fork again, so the process count doubles then doubles again (1 -> 4). Basically:

1  -> fork#1 -+-> 1 -> fork#2 -+-> 1
              |                |
              |                +-> 3
              |
              +-> 2 -> fork#2 -+-> 2
                               |
                               +-> 4
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement