Sha256: 71eda973d3bd7ec617c0bac32fcfc7fe2756ea35d0ae09f6b31346f89c1967a9

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

require 'rubygems'
require 'system_timer'

module Shellshot
  
  class Command

    alias_method :system_exec, :exec

    DEFAULT_TIMEOUT = 60 * 60 # 1 hour

    attr_accessor :pid, :status

    def exec(command, options = {})
      self.pid = fork do
        redefine_stds(options)
        system_exec(command)
      end

      begin
        wait_for(options[:timeout] || DEFAULT_TIMEOUT)
      rescue Timeout::Error => e
        terminate_child_process
        raise
      end
    end

    private

    def wait_for(seconds)
      SystemTimer.timeout(seconds) do
        Process.wait(pid)   
        self.status = $?
      end
    end

    def terminate_child_process
      if pid 
        Process.kill("KILL", pid)
        Process.wait(pid) # reaping zombie processes. Not sure if correct.
      end
    end

    def redefine_stds(options)
      $stdout.reopen(File.open(options[:stdout], "w+")) if options[:stdout]
      $stderr.reopen(File.open(options[:stderr], "w+")) if options[:stderr]

      if options[:stdall]
        combined = File.open(options[:stdall], "w+")
        $stdout.reopen(combined)
        $stderr.reopen(combined)
      end
    end
  end

  def self.exec(command, options = {})
    Shellshot::Command.new().exec(command, options)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
shellshot-0.2.0 lib/shellshot.rb