Skip to content

Instantly share code, notes, and snippets.

@ahoward

ahoward/timeoutx.rb

Created Dec 24, 2010
Embed
What would you like to do?
#! /usr/bin/env ruby
# you can timeout in ruby even when all signals are blocked by doing the work
# in a child process (relaying the value back up a pipe) and doing the
# timeout-ing in the parent. of course this only works in POSIX systems
#
require 'timeout'
def timeoutx(seconds, &block)
r, w = IO.pipe
cid = fork
parent = cid
if parent
w.close
pipe = r
Timeout.timeout(seconds) do
result = Marshal.load(pipe.read) rescue nil
end
else
r.close
pipe = w
result = block.call()
pipe.write(Marshal.dump(result)) rescue nil
exit!
end
end
timeoutx 1 do
Dir.glob('/**/**')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment