WEBrick fork and wait for the start

I have the following code where the WEBrick instance is deployed, and I want to wait until we get together before continuing with the rest of the code:

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 for the plug to finish, or even better, until WEBrick is ready to accept connections? I found a piece of code where they deal with IO.pipeboth the reader and the writer. But it does not wait for webrick to load.

Unfortunately, I did not find anything for this particular case. Hope someone can help.

+5
source share
1 answer

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
+6

All Articles