I just need to ask if my thoughts is correct at the following code:
c2=0;
c1=fork(); // fork #1
if (c1==0)
c2=fork(); // fork #2
fork(); // fork #3
if(c2>0)
fork(); // fork #4
here are my thoughts:
the parent process will create the following child’s:
Parent
–> c1 // fork #1
–> fork() // fork #3
c1
–> c2 //fork #2
–> fork() // fork #3
–> fork() // fork #4
c2
–> fork() // fork #3
is this correct?
Okay, this is going to take some analysis. It’s best to think about each process in turn:
And then create a table as follows, which steps through each process in turn:
In this table, the columns are:
Seq, the sequence number of the step.PIDthe “process” ID executing the step.CurC1andCurC2, the values forc1/c2before the step.Line,. the line number of the step.Fork?, whether a fork happens on that line.NewC1andNewC2, if thec1/c2values are changed by the step.ChPID, the process ID of the child, assuming a fork happened.ChC1andChC2, the initialc1/c2values of the child, assuming a fork happened.ChLine, the next line in the child, assuming a fork happened.ChSeq, the sequence where the child starts, assuming a fork happened.So, from this, we can see that there are a total of eight processes that were created (including the one you ran manually at the start). That doesn’t quite bear out the seven that you listed, so let’s find the missing one.
The reason I’m confident that I’m correct is because running the following program (called
xyzzy) in the background:and then executing
ps -f | grep xyzzybefore any of thesleepstatements finish, results in:In other words you have, along with the mappings from your question and the PIDs in my table:
So it’s PID 7 from my table. Following the sequence numbers back to the start, we end up with forks at
1, 7, 15, 20which would be, in your original question: