Skip to content

Instantly share code, notes, and snippets.

@shurikk
Created July 7, 2013 21:13
Show Gist options
  • Save shurikk/5944995 to your computer and use it in GitHub Desktop.
Save shurikk/5944995 to your computer and use it in GitHub Desktop.
execute shell command with a timeout
#!/usr/bin/env ruby
require 'timeout'
def exec_with_timeout(cmd, timeout)
r,w = IO.pipe
pid = Process.spawn(cmd, {[:err, :out] => w, :pgroup => true})
w.close
[begin
Timeout.timeout(timeout) do
Process.waitpid(pid, 0)
$?.exitstatus == 0
end
rescue Timeout::Error
Process.kill(15, -Process.getpgid(pid))
false
end, r.read]
end
exec_with_timeout("/path/to/long-running-command", 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment