【问题标题】:Fork WEBrick and wait for start分叉 WEBrick 并等待启动
【发布时间】:2013-03-25 14:24:06
【问题描述】:

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

很遗憾,我没有找到任何关于这个特定案例的信息。希望有人能帮忙。

【问题讨论】:

    标签: ruby process fork webrick


    【解决方案1】:

    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
    

    【讨论】:

    • 太棒了!我只用raise "Server not started" unless rd.wait(10) 替换了您的rd.read(1); rd.close,以便我可以指定超时并引发错误。感谢您的回答!
    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多