分叉WEBrick并等待启动



我有以下代码,其中WEBrick实例是分叉的,我想等到WEBrick启动后再继续执行其余代码:

require 'webrick'
pid = fork do
  server = WEBrick::HTTPServer.new({:Port => 3333, :BindAddress => "localhost"})
  trap("INT") { server.shutdown }
  sleep 10 # here is code that take some time to setup
  server.start
end
# here I want to wait till the fork is complete or the WEBrick server is started and accepts connections
puts `curl localhost:3333 --max-time 1` # then I can talk to the webrick
Process.kill('INT', pid) # finally the webrick should be killed

那么,我怎么才能等到分叉完成,或者更好地等到WEBrick准备好接受连接呢?我发现了一段代码,其中他们处理一个IO.pipe,一个阅读器和一个写入器。但这并不需要等待webrick加载。

不幸的是,我没有找到任何适合这个特殊情况的东西。希望有人能帮忙。

WEBRick::GenericServer有一些未记录的回调钩子(可悲的是,事实上,整个webrick库的文档都很差!),如:StartCallback, :StopCallback, :AcceptCallback。您可以在初始化WEBRick::HTTPServer实例时提供钩子。

所以,结合IO.pipe,你可以这样写你的代码:
require 'webrick'
PORT = 3333
rd, wt = IO.pipe
pid = fork do
  rd.close
  server = WEBrick::HTTPServer.new({
    :Port => PORT,
    :BindAddress => "localhost",
    :StartCallback => Proc.new {
      wt.write(1)  # write "1", signal a server start message
      wt.close
    }
  })
  trap("INT") { server.shutdown }
  server.start
end
wt.close
rd.read(1)  # read a byte for the server start signal
rd.close
puts `curl localhost:#{PORT} --max-time 1` # then I can talk to the webrick
Process.kill('INT', pid) # finally the webrick should be killed

最新更新