sanjep
sanjep

Reputation: 65

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

Upvotes: 0

Views: 725

Answers (2)

Gilad
Gilad

Reputation: 305

C1 won't execute the fork twice, only once. P1 will execute it twice which will result in C1 and C2. C1 will execute the second fork only. the end result is 4 processes. here is a visualization: P1 -> C2 second fork | first V fork C1 -> C3 second fork of child process

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882386

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

Upvotes: 3

Related Questions