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

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

os3-2-data-1.txt

print start
fork
fork
print end
What your program must print for os3-2-data-1.txt
100: start
100: end
101: end
102: end
103: end
Processes: 4
Tree:
100 -> 101 102
101 -> 103
Prints: start=1 end=4

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < os3-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content os3-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.