Last active
September 9, 2015 16:39
-
-
Save leandro/d60ee4cf14a58c842839 to your computer and use it in GitHub Desktop.
Right way to make process calls and use Timeout.timeout (example).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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