Created
April 17, 2012 15:11
-
-
Save rahulkmr/2406645 to your computer and use it in GitHub Desktop.
Forked timeout
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
| require 'timeout' | |
| module ForkTimeout | |
| def self.timeout(sec) | |
| if (pid = fork).nil? | |
| yield | |
| else | |
| begin | |
| Timeout::timeout(sec) { Process.waitpid(pid) } | |
| rescue Timeout::Error | |
| # The child process might complete normally after waitpid timeout. | |
| # Sending a kill signal to a non-existent process throws Errno::ESRCH | |
| # Sending a kill signal can also throw Errno::EPERM if there is permission issue. | |
| begin | |
| Process.kill("HUP", pid) | |
| Process.detach(pid) | |
| rescue Errno::ESRCH | |
| end | |
| raise | |
| end | |
| end | |
| end | |
| end | |
| ForkTimeout.timeout(1) { | |
| puts "Going to sleep" | |
| sleep 3 | |
| puts "After sleep" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment