Module: Bixby::Signal

Defined in:
lib/bixby-common/util/signal.rb

Class Method Summary collapse

Class Method Details

.trap(*signals, &block) ⇒ Thread

Helper for trapping signals and handling them via a dedicated thread

Parameters:

  • *signals (String)

    Signals to trap either as a space-separate string or array

  • block (Block)

    Callback when signal is trapped

Returns:

  • (Thread)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/bixby-common/util/signal.rb', line 11

def self.trap(*signals, &block)
  sigs = signals.flatten.map{ |s| s.split(/[\s,]/) }.flatten.sort.uniq

  trap_r, trap_w = IO.pipe

  # handle signals from a dedicated thread
  handler_thread = Thread.new do
    while true
      sig = trap_r.readline.strip
      Thread.new do
        block.call(sig)
      end
    end
  end

  sigs.each do |sig|
    Kernel.trap(sig) do
      if handler_thread && handler_thread.alive? then
        # don't bother writing if the thread is dead
        trap_w.puts(sig)
      end
    end
  end

  return handler_thread
end