23t*_*tux 5 ruby fork process 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
Run Code Online (Sandbox Code Playgroud)
那么我怎么能等到fork完成,甚至更好,直到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
Run Code Online (Sandbox Code Playgroud)