Josh Josh - 4 months ago 32
Ruby Question

How to timeout subprocess in Ruby

I want to test that a process is working so I run:

cmd = "my unix command"
results = `#{cmd}`

How can I add a timeout to the command so that if it takes more than x seconds I can assume that it is not working?


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 # ""