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:AcceptCallbackWEBRick::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 に答える