Skip to content

Instantly share code, notes, and snippets.

@tamouse
Forked from anonymous/timed_command.rb
Last active December 23, 2015 23:09
Show Gist options
  • Save tamouse/6708213 to your computer and use it in GitHub Desktop.
Save tamouse/6708213 to your computer and use it in GitHub Desktop.
[21] pry(main)> kill_subprocess('yes',2,2)
Timed Out!
Tries: 1
Timed Out!
Tries: 2
=> "yes completed"
[22] pry(main)>
require 'timeout'
def kill_subprocess(command,duration,retries)
output = ''
tries = 1
begin
cmd = IO.popen(command, :err=>[:child, :out])
Timeout.timeout(duration) do
while (line = cmd.gets) do
output << line
end
end
rescue Timeout::Error
$stdout.puts "Timed Out!"
Process.kill('KILL', cmd.pid)
$stdout.puts "Tries: #{tries}"
tries += 1
retry unless tries > retries
ensure
Process.wait(cmd.pid)
end
"#{command} completed"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment