Class: Spawner
- Inherits:
-
Object
- Object
- Spawner
- Defined in:
- lib/tootsie/spawner.rb
Instance Attribute Summary collapse
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Spawner
constructor
A new instance of Spawner.
- #on_spawn(&block) ⇒ Object
- #run(&block) ⇒ Object
- #terminate ⇒ Object
- #wait_for_children ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Spawner
Returns a new instance of Spawner.
9 10 11 12 13 14 15 |
# File 'lib/tootsie/spawner.rb', line 9 def initialize( = {}) @num_children = [:num_children] || 1 @pids = Set.new @logger = [:logger] @terminating = false @parent = true end |
Instance Attribute Details
#logger ⇒ Object (readonly)
Returns the value of attribute logger.
97 98 99 |
# File 'lib/tootsie/spawner.rb', line 97 def logger @logger end |
Instance Method Details
#on_spawn(&block) ⇒ Object
17 18 19 |
# File 'lib/tootsie/spawner.rb', line 17 def on_spawn(&block) @on_spawn = block end |
#run(&block) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/tootsie/spawner.rb', line 21 def run(&block) loop do unless @terminating while @pids.length < @num_children pid = Process.fork if pid # In parent process @pids << pid logger.info("Child PID=#{pid} spawned") else # In child process @parent = false @on_spawn.call exit(0) end end end wait_for_children break if @terminated and @pids.empty? end end |
#terminate ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/tootsie/spawner.rb', line 64 def terminate if @parent logger.info("Parent terminating, will terminate all child PIDs") @terminating = true @pids.each do |pid| logger.info("Terminating child PID=#{pid}") begin Process.kill("TERM", pid) rescue Errno::ESRCH # Ignore end end begin timeout(5) do while @pids.any? sleep(0.5) wait_for_children end end rescue Timeout::Error logger.error("Timed out waiting for children, killing them") @pids.each do |pid| logger.info("Killing child PID=#{pid}") begin Process.kill("KILL", pid) rescue Errno::ESRCH # Ignore end end end end end |
#wait_for_children ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/tootsie/spawner.rb', line 43 def wait_for_children pid = Process.waitpid(-1) if pid status = $? if status.exited? if status.exitstatus == 0 logger.info("Child PID=#{pid} exited normally") else logger.info("Child PID=#{pid} exited unexpectedly with exit code #{status.exitstatus}") end elsif status.stopped? logger.info("Child PID=#{pid} stopped unexpectedly with signal #{status.stopsig}") elsif status.signaled? logger.info("Child PID=#{pid} died unexpectedly by signal #{status.termsig}") else logger.info("Child PID=#{pid} died unexpectedly") end @pids.delete(pid) end end |