Sha256: 97d3fe1b3cb31d5a636235148d286e19330efda570645176b5e38019d8fbf26a

Contents?: true

Size: 972 Bytes

Versions: 7

Compression:

Stored size: 972 Bytes

Contents

module Bixby
  module Signal

    # Helper for trapping signals and handling them via a dedicated thread
    #
    # @param [String] *signals         Signals to trap either as a space-separate string or array
    # @param [Block] block             Callback when signal is trapped
    #
    # @return [Thread]
    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 # trap

  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
bixby-common-0.7.1 lib/bixby-common/util/signal.rb
bixby-common-0.7.0 lib/bixby-common/util/signal.rb
bixby-common-0.6.6 lib/bixby-common/util/signal.rb
bixby-common-0.6.5 lib/bixby-common/util/signal.rb
bixby-common-0.6.4 lib/bixby-common/util/signal.rb
bixby-common-0.6.3 lib/bixby-common/util/signal.rb
bixby-common-0.6.2 lib/bixby-common/util/signal.rb