ruby timeouts and system commands

luca picture luca · Nov 28, 2011 · Viewed 13.1k times · Source

I have a ruby timeout that calls a system (bash) command like this..

Timeout::timeout(10) {
  `my_bash_command -c12 -o text.txt`
}

but I think that even if the ruby thread is interrupted, the actual command keeps running in the background.. is it normal? How can I kill it?

Answer

Mladen Jablanović picture Mladen Jablanović · Nov 28, 2011

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