-
-
Save trddddd/dbc0bf4e98cf81c1d3addb935bdfa71e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Daemons | |
| def initialize | |
| @num_worker = 3 | |
| @worker_pids = [] | |
| @signal_queue = [] | |
| @handle_signals = %i[INT CLD] | |
| @self_pipe_reader, @self_pipe_writer = IO.pipe | |
| end | |
| def start | |
| $PROGRAM_NAME = 'Daemons (Parent)' | |
| spawn_workers | |
| trap_signals | |
| loop do | |
| IO.select([@self_pipe_reader]) | |
| @self_pipe_reader.read(1) | |
| case @signal_queue.shift | |
| when :INT | |
| graceful_shutdown | |
| when :CLD | |
| respawn_worker | |
| end | |
| end | |
| end | |
| def respawn_worker | |
| @worker_pids.delete(Process.wait) | |
| spawn_worker(99) | |
| puts 'CLD' | |
| end | |
| def graceful_shutdown | |
| @worker_pids.each do |wpid| | |
| Process.kill(:INT, wpid) | |
| end | |
| sleep 1 | |
| @worker_pids.each do |wpid| | |
| Process.kill(:KILL, wpid) unless Process.waitpid(wpid, Process::WNOHANG) | |
| end | |
| exit | |
| end | |
| def spawn_workers | |
| @num_worker.times do |num| | |
| spawn_worker(num) | |
| end | |
| end | |
| def trap_signals | |
| @handle_signals.each do |sig| | |
| Signal.trap(sig) do | |
| @signal_queue << sig | |
| @self_pipe_writer.write('.') | |
| end | |
| end | |
| end | |
| def spawn_worker(num) | |
| @worker_pids << Process.fork do | |
| $PROGRAM_NAME = "Daemons (Worker ##{num})" | |
| Signal.trap(:INT) { exit } | |
| worker_loop | |
| end | |
| end | |
| def worker_loop | |
| loop do | |
| sleep 60 | |
| puts 'KEKA' | |
| end | |
| end | |
| end | |
| Daemons.new.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment