Secure Timeout

I am looking for a secure way to Timeout a block of code. I noticed that
‘timeout’ (part of ruby) doesn’t work if the script is busy in a certain
function. For example:

require ‘timeout’

Timeout.timeout(5) do
Dir["//"]
end

… does NOT break after 5 seconds on my system. In fact not even
sending TERM works until Dir[] is finished. I see this also happening on
other functions, not just Dir[].

Is it possible to implement a timeout function that can’t fail? Any
ideas how?

Using mainly: Ruby 1.8.7, Linux 2.6.32, FreeBSD 8.

Thanks!

Martin

Martin B. wrote in post #970440:

I am looking for a secure way to Timeout a block of code. I noticed that
‘timeout’ (part of ruby) doesn’t work if the script is busy in a certain
function. For example:

require ‘timeout’

Timeout.timeout(5) do
Dir["//"]
end

… does NOT break after 5 seconds on my system. In fact not even
sending TERM works until Dir[] is finished. I see this also happening on
other functions, not just Dir[].

Is it possible to implement a timeout function that can’t fail? Any
ideas how?

Ruby’s timeout library uses threads, and threads in ruby 1.8 are
cooperative. So if ruby is stuck in a system call, then the timeout
can’t fire until it returns.

So I’d suggest you fork a child to do the work (see IO.popen), and read
the data from the child. If it hasn’t returned a complete reply within 5
seconds then the parent can kill it. Alternatively, poll it with
waitpid(…, Process::WNOHANG) to see if it has terminated.

Regards,

Brian.

On Sat, 25 Dec 2010 01:41:50 +0900
“ara.t.howard” [email protected] wrote:

do the work in a child. do the waiting in the parent.

https://gist.github.com/754383

Thank You & Brian - this seems to work fine!

Martin

do the work in a child. do the waiting in the parent.

https://gist.github.com/754383