1999-08-13 01:45:20 -04:00
|
|
|
#
|
|
|
|
# timeout.rb -- execution timeout
|
|
|
|
#
|
2000-05-01 05:42:38 -04:00
|
|
|
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
|
2000-05-09 00:53:16 -04:00
|
|
|
# Copyright (C) 2000 Information-technology Promotion Agency, Japan
|
2000-05-01 05:42:38 -04:00
|
|
|
#
|
1999-08-13 01:45:20 -04:00
|
|
|
#= SYNOPSIS
|
|
|
|
#
|
|
|
|
# require 'timeout'
|
|
|
|
# status = timeout(5) {
|
|
|
|
# # something may take time
|
|
|
|
# }
|
|
|
|
#
|
|
|
|
#= DESCRIPTION
|
|
|
|
#
|
|
|
|
# timeout executes the block. If the block execution terminates successfully
|
|
|
|
# before timeout, it returns true. If not, it terminates the execution and
|
|
|
|
# raise TimeoutError exception.
|
|
|
|
#
|
|
|
|
#== Parameters
|
|
|
|
#
|
|
|
|
# : timout
|
|
|
|
#
|
|
|
|
# The time in seconds to wait for block teminatation.
|
|
|
|
#
|
|
|
|
#=end
|
|
|
|
|
2001-08-20 00:29:58 -04:00
|
|
|
class TimeoutError<Interrupt
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
|
|
|
|
2002-01-15 22:37:23 -05:00
|
|
|
def timeout(sec, exception=TimeoutError)
|
2000-05-30 00:24:17 -04:00
|
|
|
return yield if sec == nil
|
1999-08-13 01:45:20 -04:00
|
|
|
begin
|
|
|
|
x = Thread.current
|
|
|
|
y = Thread.start {
|
|
|
|
sleep sec
|
2002-01-15 22:37:23 -05:00
|
|
|
x.raise exception, "execution expired" if x.alive?
|
1999-08-13 01:45:20 -04:00
|
|
|
}
|
|
|
|
yield sec
|
2001-08-20 00:29:58 -04:00
|
|
|
# return true
|
1999-08-13 01:45:20 -04:00
|
|
|
ensure
|
2001-08-20 00:29:58 -04:00
|
|
|
y.kill if y and y.alive?
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
|
|
|
end
|
2000-10-14 10:44:58 -04:00
|
|
|
|
|
|
|
if __FILE__ == $0
|
2001-08-20 00:29:58 -04:00
|
|
|
p timeout(5) {
|
|
|
|
45
|
|
|
|
}
|
|
|
|
p timeout(5) {
|
|
|
|
loop {
|
|
|
|
p 10
|
|
|
|
sleep 1
|
|
|
|
}
|
2000-10-14 10:44:58 -04:00
|
|
|
}
|
|
|
|
end
|