Sha256: bec1b565448178b7934a37a5af63212551c7aef9d2a360386559ebba926f3b36

Contents?: true

Size: 1.15 KB

Versions: 20

Compression:

Stored size: 1.15 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
      # @param &block [Proc] block to fork
      # @return [void]
      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

      def kill_process(pid)
        cancel_after(5) do
          kill_and_await('TERM', pid)
        end
      rescue Polyphony::Cancel
        kill_and_await(-9, pid)
      end

      private

      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

20 entries across 20 versions & 1 rubygems

Version Path
polyphony-0.99 lib/polyphony/adapters/process.rb
polyphony-0.98 lib/polyphony/adapters/process.rb
polyphony-0.97 lib/polyphony/adapters/process.rb
polyphony-0.96 lib/polyphony/adapters/process.rb
polyphony-0.95 lib/polyphony/adapters/process.rb
polyphony-0.94 lib/polyphony/adapters/process.rb
polyphony-0.93 lib/polyphony/adapters/process.rb
polyphony-0.92 lib/polyphony/adapters/process.rb
polyphony-0.91 lib/polyphony/adapters/process.rb
polyphony-0.90 lib/polyphony/adapters/process.rb
polyphony-0.89 lib/polyphony/adapters/process.rb
polyphony-0.87 lib/polyphony/adapters/process.rb
polyphony-0.86 lib/polyphony/adapters/process.rb
polyphony-0.85 lib/polyphony/adapters/process.rb
polyphony-0.84.1 lib/polyphony/adapters/process.rb
polyphony-0.84 lib/polyphony/adapters/process.rb
polyphony-0.83 lib/polyphony/adapters/process.rb
polyphony-0.82 lib/polyphony/adapters/process.rb
polyphony-0.81.1 lib/polyphony/adapters/process.rb
polyphony-0.81 lib/polyphony/adapters/process.rb