Search code examples
rubyprocesstimeoutterminate

ruby timeouts and system commands


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?


Solution

  • 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