How many processes are created in this snippet using fork?
Can anyone help me in understanding how this will created 19 process?
Main()
{
Fork()开发者_如何学C;
Fork() && fork () || fork ();
Fork ();
}
Try to draw a tree of the process creation and study/remember the following points:
P1. fork()
returns the pid (which is bigger tan 0) to the current process
and returns 0 in the child process.
P2. you will need to know how the
expression A() && B() || C()
is evaluated; for example if A()
returns
0 (false)
function B
will not get evaluated because 0 && whatever
is
always 0
.
Now, let's label the calls to for ease of reference:
Main()
{
Fork() /*[1]*/;
Fork() /*[2]*/ && fork ()/*[3]*/ || fork ()/*[4]*/;
Fork ()/*[5]*/;
}
I will draw the first level of process creation (and a bit of second level):
[0]
/ / \ \
[1] [2] [3] [5]
/ | \
[2] [3] [5]
The above tree means process [0] (the initial process) will execute the fork()
function numbered 1, 2, 3, and 5. Why didn't process [0]
run fork()[4]
? Because fork()[2] && fork[3]
evaluate to true already, so no point to evaluate fork()[4]
.
Apply similar concept to the process forked by fork[1]
on the second level to see why process fork[4]
was not called.
You can complete the process creation tree by applying P1 and P2 at each level of the process creation tree.
Remember that fork has a return value, either 0 or a PID (can't remember if the child gets the PID or the parent). So the && and || operators will evaluate to true when a PID is returned in which case some more processes will be forked. Hope that helps
精彩评论