Processes, fork and signals
fork and wait
fork copies the process. The child runs the block and exits; the parent gets the child's pid and must wait for it, or the process becomes a zombie:
ruby -e 'pid = fork { exit 0 }; Process.wait(pid); p $?.exitstatus'
0
The child shares the memory as a copy-on-write snapshot, so a change in the child is invisible to the parent. A result comes back through a pipe, a file or an exit status, not through a variable.
The exit status
$? is a Process::Status from the last waited child. exitstatus is the number passed to exit, success? is the boolean a caller usually wants, and termsig is set when a signal ended the process instead:
pid = fork { exit 3 } Process.wait(pid) p $?.exitstatus p $?.success?
ruby status.rb
3
false
A worker pool that reports "one job failed" reads the status, not the output. A shell script and a CI job read the same number.
Signals
trap installs a handler for a signal. The handler runs in the main thread between Ruby instructions, which is why it must be short:
trap("USR1") { puts "signal received" } child = fork do sleep 0.1 Process.kill("USR1", Process.ppid) end Process.wait(child)
ruby signal.rb
signal received
SIGTERM is the shutdown request, SIGINT is Ctrl-C, and SIGHUP is the one a server uses to reload its configuration. A long-running script traps TERM to finish the current job and exit cleanly; a script that ignores it is killed after the grace period with no cleanup.
Processes for CPU work
CRuby's GVL lets only one thread run Ruby code at a time, so threads help with waiting (network, disk) and not with arithmetic. Four processes use four cores:
ruby -e 'pids = 4.times.map { |i| fork { sleep 0.1; exit!(i) } }; p pids.map { |pid| Process.wait2(pid).last.exitstatus }'
[0, 1, 2, 3]
The child must exit! or exit explicitly: falling off the end of a fork block runs the parent's at_exit handlers twice. The status list is the four exits in pid order, which is the order the parent waited, not the order they finished.
What to watch for
A fork in a process with open connections copies the handles. A database
connection opened before the fork is shared, and two processes writing to
one socket corrupt the protocol. Reconnect in the child, or fork before
opening anything.
fork is not available on
Windows. A tool that must
run there uses threads for I/O and a separate process launch
(Process.spawn) for CPU work.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
forkreturn in the child process?Answer
nil
The parent gets the pid of the new child and the child gets nil, which is how one line of code tells the two apart.
-
What does this program print?
pid = fork { exit 7 } Process.wait(pid) p $?.exitstatus p $?.success?Answer
7 / false
The child passes 7 to exit, wait stores the status, and success? is true only for status zero.
-
What does
$?.exitstatusread afterProcess.wait?Answer
The number the child passed to exit; a child killed by a signal leaves it nil and sets termsig
The status object carries the exit code, the signal number and the success? test of the child that was waited for.
-
What does this program print?
pid = fork { Process.kill("TERM", Process.pid) } Process.wait(pid) p $?.termsig p $?.signaled?Answer
15 / true
The child ends by SIGTERM, so the status reports signal 15 and signaled? is true, while exitstatus is nil.
-
Why does a CPU-bound job use processes rather than threads on CRuby?
Answer
The GVL lets only one thread run Ruby code at a time, so processes are what use several cores
Arithmetic holds the GVL, so threads take turns on one core; four processes run on four cores.
-
What does this program print?
pids = 4.times.map { |i| fork { exit!(i) } } statuses = pids.map { |pid| Process.wait2(pid).last.exitstatus } p statusesAnswer
[0, 1, 2, 3]
Each child exits with its own index, and the parent waits in pid order, so the statuses come back in that order.
-
What does this program print?
trap("USR2") { puts "ping" } child = fork do sleep 0.05 Process.kill("USR2", Process.ppid) end Process.wait(child)Answer
ping
The child signals its parent, the handler runs in the parent between instructions and prints once, and the wait then returns.
-
What is a zombie process?
Answer
A finished child whose exit status the parent never collected
The child is gone but its status stays in the table until wait or wait2 reads it, which is why every fork is waited for.
-
Which signals do TERM, INT and HUP stand for?
Answer
TERM asks a process to stop, INT is Ctrl-C, and HUP is the reload request a server traps
A long job traps TERM to finish its current work, INT is the interrupt key, and SIGHUP is the traditional reload.
-
What are the two limits of
forkthat a portable tool must handle?Answer
It does not exist on Windows, and a connection opened before the fork is shared by both processes
Windows has no fork, and a handle copied into the child corrupts a protocol when both processes write to it, so the child reconnects or the fork comes first.
Article author: Arthur Isaev