Sometimes we don't need to be quite so hands-on: we'd like to give
the subprocess its assignment and then go on about our business. Some
time later, we'll check in with it to see if it has finished. For
instance, we might want to kick off a long-running external sort.
exec("sort testfile > output.txt") if fork == nil
# The sort is now running in a child process
# carry on processing in the main program
# then wait for the sort to finish
Process.wait
|
The call to
Kernel::fork
returns a process id in the parent, and
nil
in the child, so the child process will perform the
Kernel::exec
call and run sort. Sometime later, we issue a
Process::wait
call, which waits for the sort to complete (and
returns its process id).
If you'd rather be notified when a child exits (instead of just
waiting around), you can set up a signal handler using
Kernel::trap
(described on page 427). Here we set
up a trap on
SIGCLD
, which is the signal sent on ``death of child
process.''
trap("CLD") {
pid = Process.wait
puts "Child pid #{pid}: terminated"
exit
}
exec("sort testfile > output.txt") if fork == nil
# do other stuff...
|
produces:
Child pid 31842: terminated
|