Created
January 25, 2012 22:31
-
-
Save kwilczynski/1679285 to your computer and use it in GitHub Desktop.
EventMachine with fork and children ... Mark II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'eventmachine' | |
require 'socket' | |
SOCKET = '/tmp/test.socket' | |
module Connection | |
def receive_data(data) | |
puts "\t#{data}" | |
end | |
end | |
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 | |
EventMachine.run do | |
puts "Father PID: #{Process.pid}" | |
EventMachine.start_unix_domain_server(SOCKET, 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 | |
s = UNIXSocket.new(SOCKET) | |
Signal.trap('SIGUSR1') do | |
begin | |
s.close unless s.closed? | |
rescue IOError | |
end | |
EventMachine.stop_event_loop | |
end | |
Signal.trap('SIGCHLD') {} | |
Signal.trap('EXIT') {} | |
EventMachine.add_periodic_timer(5) do | |
s.send("Child[#{i}](#{Process.pid}): #{Time.now.to_s}", 0) | |
end | |
end | |
children << pid | |
puts "Child[#{i}] PID: #{pid}" | |
Process.detach(pid) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment