Skip to content

Instantly share code, notes, and snippets.

@leandro
Last active September 9, 2015 16:39
Show Gist options
  • Save leandro/d60ee4cf14a58c842839 to your computer and use it in GitHub Desktop.
Save leandro/d60ee4cf14a58c842839 to your computer and use it in GitHub Desktop.
Right way to make process calls and use Timeout.timeout (example).
def run_with_timeout(cmd, limit)
Open3.popen3(cmd) do |_, stdout, stderr, wait_thr|
output, pid = [], wait_thr.pid
begin
Timeout.timeout(limit) do
output = [stdout.read, stderr.read]
Process.wait(pid)
end
rescue Errno::ECHILD
rescue Timeout::Error
Process.kill('HUP', pid)
fail
end
output
end
end
run_with_timeout('sleep 5; echo 1', 10) # ["1\n", ""]
run_with_timeout('sleep 11; echo 2', 10) # throws Timeout::Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment