Ruby Timeouts and System Commands

ruby timeouts and system commands

I think you have to kill it manually:

require 'timeout'

puts 'starting process'
pid = Process.spawn('sleep 20')
begin
Timeout.timeout(5) do
puts 'waiting for the process to end'
Process.wait(pid)
puts 'process finished in time'
end
rescue Timeout::Error
puts 'process not finished in time, killing it'
Process.kill('TERM', pid)
end

How to timeout subprocess in Ruby

Ruby ships witrh the Timeout module.

require 'timeout'
res = ""
status = Timeout::timeout(5) {res = `#{cmd}`} rescue Timeout::Error

# a bit of experimenting:

res = nil
status = Timeout::timeout(1) {res = `sleep 2`} rescue Timeout::Error
p res # nil
p status # Timeout::Error

res = nil
status = Timeout::timeout(3) {res = `sleep 2`} rescue Timeout::Error
p res # ""
p status # ""

Kill linux command in ruby if timed-out

Not sure if this illustrates it but for example 2 ruby files:

#slow_proceess.rb
puts 'starting.... waiting...'

10.times do
puts "slow process runing..."
sleep 1
end

puts 'done exiting'

#fast.rb
pid = Process.spawn('ruby slow_process.rb')
# after x seconds we can kill the process with
`kill -9 #{pid}`

Or in your example use instance variable to access it outside of the block and also rescue error (thanks @tadman):

begin
Timeout::timeout(5) {
@pid = Process.spawn('sleep 30; echo 1')
}
rescue Timeout::Error
puts "#{@pid} process has timed out"
end

# do stuff

Changing behavior of gets, when reading from command line, in Ruby

Check the docs:

If Kernel.gets sees that ARGV is set, it uses them as filenames to
feed instead of reading from stdin. So use an expicit: $stdin.gets

Best way of implementing timeouts on ruby sockets

From what I understand now, it is easiest (not necessarily best--depends on your needs) just to avoid this problem of trying to have my socket connection attempt time out as well as my socket.read time out. Since my script is simple and I am using Ruby 1.8.7, I am using the system_timer gem (ruby's timeout library is not reliable for Ruby 1.8.x and system_timer gets around timeout's issues for Ruby 1.8.x).

http://systemtimer.rubyforge.org/

The documentation is good.



Related Topics



Leave a reply



Submit