父进程在一个单独的线程中启动一个 EventMachine 服务器,并在主线程中监视和重生死掉的工人。
子进程启动另一个 EventMachine 服务器,然后在五秒后退出。
问题是当新的子进程启动时,父进程的所有连接的客户端都断开了。
我应该做些什么来正确地做到这一点?
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