WEBRick::GenericServer
has some callback hooks which are undocumented (sadly, in fact, the whole webrick library is poorly documented!), such as :StartCallback
, :StopCallback
, :AcceptCallback
. You can provide hooks when initializing a WEBRick::HTTPServer
instance.
So, combined with IO.pipe
, you can write your code like this:
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