considering the following instruction:
for(int i = 0; i < 3; i++)
fork();
I try to figure out the number of created process and the steps of graph creation.
so the code above is equivalent than:
fork();
fork();
fork();
The official answer to this problem is illustrated with this graph:
I am not able to visualize how this graph is created.
This is how I would have drawn the graph.
-
so, the first fork will create a child copy (p2) of the parent process (p1). We have 2 process.
-
the second fork, will duplicate p1 and p2 parents, by creating child process (p3 and p4).
-
The third fork, will duplicate p1, p2, p3 and p4, by creating child process (p5, p6, p7, p8)
How can I obtain the same graph as my teacher?
If you want a graph similar to the official answer, try to stop thinking about how things run concurrently and instead concentrate on the generations of processes (parents, children, grandchildren and so on).
At the start, there is one process
p0, with three forks to go. When doing those three forks, it createsp1with two forks to go,p2with one fork to go andp3with no forks left. Thenp0exits (onlyp1,p2andp3remain).We can toss away
p3since it has no forks left, leaving justp1andp2).Process
p1then executes its second fork producingp4with one fork left, then executes the third fork makingp5with no forks left.p1is now done and exits (p2,p4andp5remain).Similar to
p3,p5can be tossed because it has no forks left. This leavesp2andp4.Similarly,
p2had one fork left so it createsp6with no forks left. Then bothp2andp6exit due to having no forks left, leavingp4.Process
p4had one fork left so it createsp7with no forks, and they both then exit.By drawing the chart with the depth based on parentage rather than when processes are started (although the starting time(a) controls where the process exists horizontally at a specific depth, eg, see
p1,p2andp3), your diagram should match the one given.So think of it this way:
(a) Keep in mind that starting time as defined here is when the process comes into existence – the order in which processes do actual useful work also depends on the vagaries of scheduling.