What will this Ruby code print?
pid = fork do puts "Child process" end Process.wait(pid) puts "Parent process"
Remember the parent waits for the child to finish before printing.
The fork creates a child process that prints first. The parent waits for the child with Process.wait before printing.
What is the value of x printed by this Ruby code?
x = 10 pid = fork do x = 20 puts x end Process.wait(pid) puts x
Child and parent have separate memory after fork.
The child changes x to 20 and prints it. The parent keeps x as 10 and prints it after waiting.
What is wrong with this Ruby code?
pid = fork do puts "Child" end puts "Parent"
Think about what happens if the parent exits before the child finishes.
The parent does not wait for the child, so the child runs independently. The code does not hang, but the child may print after the parent exits. The code does not hang indefinitely.
How many processes will be created and print "Hello" in this Ruby code?
3.times do fork do puts "Hello" end end Process.waitall
Each fork creates one child process.
The loop runs 3 times, each time creating one child process that prints "Hello". So 3 child processes print "Hello".
What is the output of this Ruby code?
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
Remember each fork creates a new process with its own copy of variables.
The innermost child increments x to 2 and prints it. Its parent increments x to 1 and prints it after waiting. The original parent prints 0 because its x is unchanged.