Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save elvuel/1986250 to your computer and use it in GitHub Desktop.

Select an option

Save elvuel/1986250 to your computer and use it in GitHub Desktop.
EventMachine with fork and children ...
require 'rubygems'
require 'eventmachine'
children = []
Signal.trap('SIGINT') do
EventMachine.next_tick { EventMachine.stop_event_loop }
end
Signal.trap('EXIT') do
puts "Killing #{children.size} children ..."
children.each do |pid|
Process.kill('SIGUSR1', pid) rescue Exception
end
end
channel = EventMachine::Channel.new
EventMachine.run do
puts "Father PID: #{Process.pid}"
channel.subscribe {|m| puts "\t#{m}" }
EventMachine.add_periodic_timer(1) do
puts "Father(#{Process.pid}): #{Time.now.to_s}"
end
4.times do |i|
pid = EventMachine.fork_reactor do
Signal.trap('SIGUSR1') { EventMachine.stop_event_loop }
Signal.trap('SIGCHLD') {}
Signal.trap('EXIT') {}
EventMachine.add_periodic_timer(5) do
channel.push "Child[#{i}](#{Process.pid}): #{Time.now.to_s}"
end
end
children << pid
puts "Child[#{i}] PID: #{pid}"
Process.detach(pid)
end
end
@chergik
Copy link
Copy Markdown

chergik commented Feb 13, 2013

On SIGINT after "stop_event_loop" you should do

children.each do |pid|
Process.kill('SIGUSR1', pid) rescue Exception
end

as in "EXIT". In other case you will see child processes in ps aux after parent gone. Hate zombie.

Copy link
Copy Markdown

ghost commented Apr 29, 2014

I tried this, but the channel is not actually enabling communication across processes :(. Change the channel.subscribe puts to also write the Process.pid, and you'll see there's a separate channel for each process.

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