2013-03-25 13 views
5

ho il seguente codice, dove è biforcuta un'istanza WEBrick, e voglio aspettare fino al webrick viene avviato, prima di continuare con il resto del codice:Forcella WEBrick e attendere inizio

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 

Quindi, come posso aspettare che il fork sia completo, o meglio ancora fino a quando il WEBrick è pronto ad accettare le connessioni? Ho trovato un pezzo di codice in cui hanno a che fare con un IO.pipe e un lettore e uno scrittore. Ma non aspetta che Webrick si carichi.

Purtroppo non ho trovato nulla per questo caso specifico. Spero che qualcuno possa aiutarti.

risposta

6

WEBRick::GenericServer presenta alcuni ganci di richiamata che non documentati (purtroppo, infatti, l'intera libreria webrick è scarsamente documentata!), come :StartCallback, :StopCallback, :AcceptCallback. È possibile fornire hook durante l'inizializzazione di un'istanza WEBRick::HTTPServer.

Così, in combinazione con IO.pipe, è possibile scrivere il codice come questo:

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

Meraviglioso! Ho solo sostituito il tuo 'rd.read (1); rd.close' con 'raise" Server non avviato "a meno che rd.wait (10)' in modo da poter specificare un timeout e generare un errore. Grazie per la risposta! – 23tux