[英]Fork WEBrick and wait for start
I have the following code, where a WEBrick instance is forked, and I want to wait till the webrick is started up, before continuing with the rest of the code: 我有以下代码,其中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
So how can I wait till the fork is complete, or even better till the WEBrick is ready to accept connections? 那么我怎么能等到fork完成,甚至更好,直到WEBrick准备好接受连接? I found a piece of code where they deal with a IO.pipe
and a reader and a writer. 我发现了一段代码,它们处理IO.pipe
,读者和作者。 But that doesn't wait for webrick to load. 但这并不等待webrick加载。
Unfortunately I haven't found anything for this specific case. 不幸的是,我没有找到任何针对这个具体案例 Hope someone can help. 希望有人能提供帮助。
WEBRick::GenericServer
has some callback hooks which are undocumented ( sadly, in fact, the whole webrick library is poorly documented! ), such as :StartCallback
, :StopCallback
, :AcceptCallback
. WEBRick::GenericServer
有一些未记录的回调挂钩( 遗憾的是,事实上,整个webrick库记录很少! ),例如:StartCallback
, :StopCallback
, :AcceptCallback
。 You can provide hooks when initializing a WEBRick::HTTPServer
instance. 初始化WEBRick::HTTPServer
实例时,可以提供挂钩。
So, combined with IO.pipe
, you can write your code like this: 因此,结合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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.