Skip to content

Instantly share code, notes, and snippets.

@ramonmaruko
Created January 30, 2013 05:40
Show Gist options
  • Save ramonmaruko/4670949 to your computer and use it in GitHub Desktop.
Save ramonmaruko/4670949 to your computer and use it in GitHub Desktop.
EchoServer is unbounded after child with running EventMachine is exited.
require 'eventmachine'
module EchoServer
def post_init
puts "-- someone connected to the echo server!"
end
def receive_data data
send_data ">>>you sent: #{data}"
close_connection if data =~ /quit/i
end
def unbind
puts "-- someone disconnected from the echo server!"
end
end
puts "Forking..."
def start_echo_server
Thread.new {
puts "Starting Echo server"
EventMachine.run {
EventMachine.start_server "127.0.0.1", 8081, EchoServer
}
}
end
def spawn_workers
if @pid = fork
@started = start_echo_server unless @started
else
puts "Child #{$$}: Sleeping for 5 seconds"
EventMachine.run {
EventMachine.start_server "127.0.0.1", 8082, EchoServer
EventMachine.add_timer(5) do
puts "Child #{$$}: exiting..."
exit
end
}
end
@pid
end
spawn_workers
if @pid
begin
# check if we have any child process that died
wpid, status = Process.waitpid2(-1, Process::WNOHANG)
wpid or (sleep 0.1 && next)
spawn_workers
rescue Errno::ECHILD
break
end while true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment