0
0
Rubyprogramming~20 mins

Process forking for parallelism in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Fork Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of simple forked process

What will this Ruby code print?

Ruby
pid = fork do
  puts "Child process"
end
Process.wait(pid)
puts "Parent process"
AChild process
BChild process\nParent process
CParent process\nChild process
DParent process
Attempts:
2 left
💡 Hint

Remember the parent waits for the child to finish before printing.

Predict Output
intermediate
2:00remaining
Variable value after fork

What is the value of x printed by this Ruby code?

Ruby
x = 10
pid = fork do
  x = 20
  puts x
end
Process.wait(pid)
puts x
A10\n20
B20\n20
C20\n10
D10\n10
Attempts:
2 left
💡 Hint

Child and parent have separate memory after fork.

🔧 Debug
advanced
2:00remaining
Why does this forked code hang?

What is wrong with this Ruby code?

Ruby
pid = fork do
  puts "Child"
end
puts "Parent"
AParent does not wait for child, so child may still run after parent exits
BFork block syntax is incorrect, causing infinite loop
CMissing <code>Process.wait(pid)</code> causes parent to hang
DChild process never prints because of missing <code>puts</code>
Attempts:
2 left
💡 Hint

Think about what happens if the parent exits before the child finishes.

Predict Output
advanced
2:00remaining
Number of processes created

How many processes will be created and print "Hello" in this Ruby code?

Ruby
3.times do
  fork do
    puts "Hello"
  end
end
Process.waitall
A4
B1
C0
D3
Attempts:
2 left
💡 Hint

Each fork creates one child process.

Predict Output
expert
3:00remaining
Output of nested forks with variable increments

What is the output of this Ruby code?

Ruby
x = 0
pid1 = fork do
  x += 1
  pid2 = fork do
    x += 1
    puts x
  end
  Process.wait(pid2)
  puts x
end
Process.wait(pid1)
puts x
A2\n1\n0
B1\n2\n0
C0\n1\n2
D2\n2\n2
Attempts:
2 left
💡 Hint

Remember each fork creates a new process with its own copy of variables.