Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout subprocess in Ruby

Tags:

ruby

timeout

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?

like image 614
Josh Avatar asked Feb 20 '23 06:02

Josh


1 Answers

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 # ""
like image 108
steenslag Avatar answered Mar 03 '23 09:03

steenslag