Skip to content

Instantly share code, notes, and snippets.

@rahulkmr
Created April 17, 2012 15:11
Show Gist options
  • Select an option

  • Save rahulkmr/2406645 to your computer and use it in GitHub Desktop.

Select an option

Save rahulkmr/2406645 to your computer and use it in GitHub Desktop.
Forked timeout
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