The following code
require 'timeout'
begin
timeout(20) do # Line 4
result = `hostname`
end # Line 6
rescue Timeout::Error
puts "Timeout"
exit
end
puts "Result:" + result # Line 12
throws the error
issue.rb:12:in
<main>': undefined local variable or method
result' for main:Object (NameError)
but if I comment out the timeout element (lines 4 and 6), it works fine. I have tried using IO.popen, IO.select etc but none of this helps. I've used this timeout technique in many other areas and it worked fine.
It doesn't appear to be related to the timeout value as I have experimented with much larger and smaller values.
Am using Ruby 1.92 on Windows XP. Any help much appreciated.
p.s. My original problem was not running "hostname" but a more complex SQL Server batch job. As a bonus point, would a long running system task that exceeded the timeout be automatically killed? I have read lots of posts about the timeout library not honouring timeouts when busy running system tasks?
The result
variable is being defined inside the timeout block, so it's not visible in the outer scope. You should initialize it before:
result = nil
begin
timeout(20) do # Line 4
result = `hostname`
end # Line 6
rescue Timeout::Error
...