Skip to content

Instantly share code, notes, and snippets.

@zlx
Created July 2, 2014 13:41
Show Gist options
  • Save zlx/1e5eaea0a6dbb551587b to your computer and use it in GitHub Desktop.
Save zlx/1e5eaea0a6dbb551587b to your computer and use it in GitHub Desktop.
child_processes = 3
dead_processes = 0
# We fork 3 child processes.
child_processes.times do
fork do
# They sleep for 3 seconds.
sleep 3
end
end
# Our parent process will be busy doing some intense mathematics.
# But still wants to know when one of its children exits.
# By trapping the :CHLD signal our process will be notified by the kernel # when one of its children exits.
trap(:CHLD) do
# Since Process.wait queues up any data that it has for us we can ask for it
# here, since we know that one of our child processes has exited.
puts Process.wait
dead_processes += 1
# We exit explicitly once all the child processes are accounted for.
exit if dead_processes == child_processes
end
# Work it.
loop do
(Math.sqrt(rand(44)) ** 8).floor
sleep 1
end
@zlx
Copy link
Author

zlx commented Jul 2, 2014

begin
  while pid = Process.wait(-1, Process::WNOHANG)
    puts pid
    dead_processes += 1
    # We exit ourselves once all the child processes are accounted for. 
    exit if dead_processes == child_processes
  end
rescue Errno::ECHILD 
end

改成这样可以保证每次 children process death 都能 catch。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment