我有以下代码,其中有一个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加载。
不幸的是,我还没有为这个特定的案例找到任何东西。希望有人能帮上忙。
发布于 2013-03-25 23:11:52
WEBRick::GenericServer有一些没有文档记录的回调钩子(遗憾的是,实际上整个are库都没有文档记录!),比如: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 killedhttps://stackoverflow.com/questions/15617347
复制相似问题