Advertisement
DRVTiny

KemaForkCorrect.cr

May 7th, 2018
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.65 KB | None | 0 0
  1. require "kemal"
  2. require "logger"
  3.  
  4. log = Logger.new(STDERR)
  5. log.level = Logger::DEBUG
  6.  
  7. get "/" do
  8.   "Hello World! I am a process with pid #{Process.pid}"
  9. end
  10.  
  11. sgnl_kemal_stop = Channel(Int32).new
  12. spawn do
  13.     Kemal.run { |cfg| cfg.server.not_nil!.bind(reuse_port: true) }
  14.     sgnl_kemal_stop.send(1)
  15. end
  16.  
  17. children_procs = [] of Process
  18. 15.times do
  19.     children_procs << ( child_p = Process.fork do
  20.         log.info("I am a child process with pid #{Process.pid}")
  21.         Signal::TERM.trap do
  22.             log.warn("Process #{Process.pid} received TERM signal, so we have to emergency cleanup and exit now")
  23.             Kemal.stop
  24.             exit(0)
  25.         end
  26.         exit_code = sgnl_kemal_stop.receive
  27.         log.error("[#{Process.pid}] Ooops. How is that possible?")
  28.         exit(1)
  29.     end )
  30. end
  31.  
  32. sgnl_sighup_rcvd = Channel(Int32).new
  33. {% for sgnl in %w(HUP TERM INT) %}
  34. Signal::{{sgnl.id}}.trap do
  35.     sgnl_sighup_rcvd.send(1)
  36. end
  37. {% end %}
  38.  
  39. log.info( "I am a main process with pid #{Process.pid}. Send me HUP signal to terminate Kemal server gracefully" )
  40.  
  41. x = sgnl_sighup_rcvd.receive
  42. log.info( "(some) signal received by master process #{Process.pid}. We have to terminate our children (by pid):\n\t[" + children_procs.map {|p| p.pid}.join(", ") + "]" )
  43.  
  44. children_procs.each do |child_p|
  45.     child_pid = child_p.pid
  46.     if child_p.terminated?
  47.         log.warn( "Child ##{child_pid} already terminated" )
  48.     else
  49.         log.debug("Sending signal TERM (15) to process #{child_pid}")
  50.         child_p.kill
  51.         child_p.wait
  52.     end
  53.     log.error( "Cant terminate child ##{child_pid}" ) unless child_p.terminated?
  54. end
  55.  
  56. Kemal.stop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement