Sha256: 5395c79cfa4465dce247c9714928b84c719c72848abeeb448e2c02b003d1d004

Contents?: true

Size: 1.07 KB

Versions: 3

Compression:

Stored size: 1.07 KB

Contents

# encoding: utf-8
require 'timeout'
require 'ostruct'

module TestServer
  class CommandRunner

    private

    attr_reader :timeout

    public

    def initialize(timeout:)
      @timeout = timeout
    end

    def run(command)
      # stdout, stderr pipes
      rout, wout = IO.pipe
      rerr, werr = IO.pipe

      result = OpenStruct.new

      begin
        result.pid = Process.spawn(command, :out => wout, :err => werr)
        _, status = Timeout::timeout(timeout) { Process.wait2(result.pid) }

        result.status = status.exitstatus
      rescue Timeout::Error
        Process.kill 'KILL', result.pid
        result.status = 99
      end

      # close write ends so we could read them
      wout.close
      werr.close

      result.stdout = rout.readlines
      result.stderr = rerr.readlines

      # dispose the read ends of the pipes
      rout.close
      rerr.close

      result
    end
  end
end

module TestServer
  module RunCommand
    def run_command(command, timeout: 5)
      runner = CommandRunner.new(timeout: timeout)
      runner.run(command)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
test_server-0.5.2 lib/test_server/command_runner.rb
test_server-0.5.1 lib/test_server/command_runner.rb
test_server-0.5.0 lib/test_server/command_runner.rb