Sha256: 86d45bcaf6f911471fceafe0e313de7956c3d4fd769935105fc81f7ae6d4c941

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

require 'benchmark'
require 'open3'

module Frontkick
  class Command
    def self.exec(cmd, opts = {})
      stdout, stderr, exit_code, duration = nil
      stdin, out, err, wait_thr, pid = nil

      cmd_array = cmd.kind_of?(Array) ? cmd : [cmd]
      begin
        timeout(opts[:timeout]) do # nil is for no timeout
          duration = Benchmark.realtime do
            stdin, out, err, wait_thr = Open3.popen3(*cmd_array)
            stdin.close
            pid = wait_thr.pid
            stdout = out.read
            stderr = err.read
            exit_code = wait_thr.value.exitstatus
            process_wait(pid)
          end
        end
      rescue Timeout::Error => e
        Process.kill('SIGINT', pid)
        exit_code = wait_thr.value.exitstatus
        process_wait(pid)
        duration = opts[:timeout]
        stdout = ""
        stderr = "pid:#{pid}\tcommand:#{cmd_array.join(' ')} is timeout!"
      ensure
        stdin.close if stdin and !stdin.closed?
        out.close if out and !out.closed?
        err.close if err and !err.closed?
        wait_thr.kill if wait_thr and !wait_thr.stop?
      end
      
      CommandResult.new(stdout, stderr, exit_code, duration)
    end

    def self.process_wait(pid)
      begin
        pid, status = Process.waitpid2(pid) # wait child processes finish
      rescue Errno::ECHILD => e
        # no child process
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
frontkick-0.1.0 lib/frontkick/command.rb