Sha256: c08c66d9988d2693166f743e0eab73d73fef1b8f1eee5544ca2de56c2adc3aa0

Contents?: true

Size: 1.42 KB

Versions: 12

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module Polyphony
  # Process extensions
  module Process
    class << self

      # Watches a forked or spawned process, waiting for it to terminate. If
      # `cmd` is given it is spawned, otherwise the process is forked with the
      # given block.
      #
      # If the operation is interrupted for any reason, the spawned or forked
      # process is killed.
      #
      # @param cmd [String, nil] command to spawn
      # @return [true]
      def watch(cmd = nil, &block)
        terminated = nil
        pid = cmd ? Kernel.spawn(cmd) : Polyphony.fork(&block)
        Polyphony.backend_waitpid(pid)
        terminated = true
      ensure
        kill_process(pid) unless terminated || pid.nil?
      end

      # Kills the given pid, waiting for it to terminate, with a timeout of 5
      # seconds.
      #
      # @param pid [Integer] pid
      def kill_process(pid)
        cancel_after(5) do
          kill_and_await('TERM', pid)
        end
      rescue Polyphony::Cancel
        kill_and_await(-9, pid)
      end

      private

      # Kills the given process with given signal, waiting for it to terminate.
      #
      # @param sig [String, Symbol, Integer] signal to use
      # @param pid [Integer] pid
      def kill_and_await(sig, pid)
        ::Process.kill(sig, pid)
        Polyphony.backend_waitpid(pid)
      rescue Errno::ESRCH
        # process doesn't exist
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
polyphony-1.6 lib/polyphony/adapters/process.rb
polyphony-1.5 lib/polyphony/adapters/process.rb
polyphony-1.4 lib/polyphony/adapters/process.rb
polyphony-1.3 lib/polyphony/adapters/process.rb
polyphony-1.2.1 lib/polyphony/adapters/process.rb
polyphony-1.2 lib/polyphony/adapters/process.rb
polyphony-1.1.1 lib/polyphony/adapters/process.rb
polyphony-1.1 lib/polyphony/adapters/process.rb
polyphony-1.0.2 lib/polyphony/adapters/process.rb
polyphony-1.0.1 lib/polyphony/adapters/process.rb
polyphony-1.0 lib/polyphony/adapters/process.rb
polyphony-0.99.6 lib/polyphony/adapters/process.rb