THINK FIRST·CODE LATER

← All labs

fork() explorer: build the process tree

Problem

Simulate a program made of fork and print statements executed by a process with PID 100.

Input: one statement per line until the end of input: fork or print LABEL. Every process alive at a statement executes it, in increasing PID order:

  • fork: each alive process creates one child with the next free PID (101, 102, …, assigned in that order); the child continues with the next statement, like the parent.
  • print LABEL: each alive process prints PID: LABEL.

At the end print:

Processes: n
Tree:
100 -> 101 102 104
101 -> 103 105
...

listing, for every process that has children (in increasing PID order), its children in increasing order. Then Prints: LABEL=k ... giving how many times each label was printed, in the order the labels first appear.

Input:

print start
fork
fork
print end

Output:

100: start
100: end
101: end
102: end
103: end
Processes: 4
Tree:
100 -> 101 102
101 -> 103
Prints: start=1 end=4

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.