From: "ara.t.howard" Date: 2008-08-09T06:26:17+09:00 Subject: Re: Non-Threaded Timeout? On Aug 8, 2008, at 7:58 AM, Bryan Richardson wrote: > Hell all, > > I'm looking for a way to implement a non-threaded timeout. I am > running > some Monte Carlo simulations using an external application via an OLE > interface. There are times where the external application seems to > hang > up, so I'm looking for a way to detect this and continue on with my > simulation if the external application takes too long. > > Any suggestions? slightly more complete - may need tweaks for windoze.... cfp:~ > cat a.rb Timing.out(2) do p 'works' end Timing.out(1) do begin sleep 2 rescue Timed.out p 'times out' end end Timing.out(1) do sleep 2 p 'blows up' end BEGIN { module Timing class Error < ::StandardError; end def Timing.out *seconds, &block if seconds.empty? return Error else seconds = Float seconds.first end pid = Process.pid signaler = IO.popen "ruby -e'sleep #{ seconds }; Process.kill(:TERM.to_s, #{ pid }) rescue nil'" thread = Thread.current handler = Signal.trap('TERM'){ thread.raise Error, seconds.to_s } begin block.call ensure Process.kill 'TERM', signaler.pid rescue nil Signal.trap('TERM', handler) end end ::Timed = Timing end } cfp:~ > ruby a.rb "works" "times out" a.rb:34:in `out': 1.0 (Timing::Error) from a.rb:14:in `call' from a.rb:14:in `sleep' from a.rb:14 from a.rb:36:in `call' from a.rb:36:in `out' from a.rb:13 a @ http://codeforpeople.com/ -- we can deny everything, except that we have the possibility of being better. simply reflect on that. h.h. the 14th dalai lama