Module: MultiTimeout

Defined in:
lib/multi_timeout.rb,
lib/multi_timeout/version.rb

Defined Under Namespace

Modules: CLI

Constant Summary collapse

TICK =
1
VALID_SIGNAL =
/^(-(\d+|[A-Z\d]+))$/
VERSION =
"1.1.0"

Class Method Summary collapse

Class Method Details

.run(command, timeouts: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/multi_timeout.rb', line 9

def run(command, timeouts: nil)
  # spawn process in a separate group so we can take it down completely and not leave any children
  pid = Process.spawn({}, *command, pgroup: true)
  gid = Process.getpgid(pid)

  Thread.new do
    elapsed = 0
    loop do
      break if dead?(pid)

      timeouts.each do |signal, max|
        if elapsed >= max
          timeouts.delete(signal)
          puts "Killing '#{truncate(Array(command).join(" "), 30)}' with signal #{signal} after #{elapsed} seconds"
          Process.kill(signal, -gid)
        end
      end
      elapsed += TICK
      sleep TICK
    end
  end

  Process.wait2(pid).last.exitstatus || 1
end