Reputation: 11
I am having problems with C code about processes that are created with fork given by our professor to figure out the number of processes that it creates.
pid1 = fork();
if (pid1 != 0) {
pid2 = fork();
pid3 = fork();
}
else {
pid4 = fork();
}
Upvotes: 0
Views: 54
Reputation: 56905
Running the code is only somewhat helpful (and can't be done during the exam!)--better to draw a process tree. The rules are that every child process starts execution after the fork
call that spawned it, parents have nonzero pid
and children have a pid
of zero.
main
/ | \
pid1 pid2 pid3
/ |
pid4 pid3
We can see main
spawns three children, pid1
, pid2
and pid3
(pid1
is trivial and the other two are spawned in the true if
block). pid1
goes on to the else
portion of the conditional and spawns pid4
before finishing. pid2
is the only trick: it spawns again at pid3
because that's where its execution starts.
Answer:
6 processes in total are created (
main
and 5 children)
Upvotes: 2