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?
>
> --
> Thanks!
> Bryan
> -- 
> Posted via http://www.ruby-forum.com/.
>

something like this should be able to work, even on windows....


cfp:~ > cat a.rb
require 'timeout'

def timeout seconds, &block
   pid = Process.pid
   signaler = IO.popen "ruby -e'sleep #{ seconds };  
Process.kill(:TERM.to_s, #{ pid }) rescue nil'"
   handler = Signal.trap('TERM'){ raise 'timed out...' }
   begin
     block.call
   ensure
     Process.kill 'TERM', signaler.pid rescue nil
     Signal.trap('TERM', handler)
   end
end

timeout(2){ p 'works' }
timeout(1){ sleep 2; p 'does not work' }



cfp:~ > ruby a.rb
"works"
a.rb:6:in `timeout': timed out... (RuntimeError)
         from a.rb:16:in `call'
         from a.rb:16:in `sleep'
         from a.rb:16
         from a.rb:8:in `call'
         from a.rb:8:in `timeout'
         from a.rb:16


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