5

我有以下代码,其中一个 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 加载。

不幸的是,我没有找到任何关于这个特定案例的东西。希望有人可以提供帮助。

4

1 回答 1

9

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
于 2013-03-25T15:11:51.910 回答