Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Created January 28, 2012 00:36
Show Gist options
  • Save kwilczynski/1691810 to your computer and use it in GitHub Desktop.
Save kwilczynski/1691810 to your computer and use it in GitHub Desktop.
EventMachine with fork and children ... Mark III
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
module Connection
def receive_data(data)
puts "\t#{data}"
end
end
pipe = IO.pipe
EventMachine.run do
puts "Father PID: #{Process.pid}"
read = EventMachine.attach(pipe[0], Connection)
EventMachine.add_periodic_timer(1) do
puts "Father(#{Process.pid}): #{Time.now.to_s}"
end
4.times do |i|
pid = EventMachine.fork_reactor do
read.close_connection
write = EventMachine.attach(pipe[1])
Signal.trap('SIGUSR1') { EventMachine.stop_event_loop }
Signal.trap('SIGCHLD') {}
Signal.trap('EXIT') {}
EventMachine.add_periodic_timer(5) do
write.send_data "Child[#{i}](#{Process.pid}): #{Time.now.to_s}"
end
end
children << pid
puts "Child[#{i}] PID: #{pid}"
Process.detach(pid)
end
end
@kwilczynski
Copy link
Author

Add in SIGINT handler:

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

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