Ruby超时和系统命令



我有一个像这样调用系统(bash)命令的ruby超时。

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

,但我认为,即使ruby线程被中断,实际的命令继续在后台运行。这正常吗?我怎样才能杀死它?

我认为你必须手动kill:

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

为了正确地停止生成的进程树(不仅仅是父进程),应该考虑这样做:

def exec_with_timeout(cmd, timeout)
  pid = Process.spawn(cmd, {[:err,:out] => :close, :pgroup => true})
  begin
    Timeout.timeout(timeout) do
      Process.waitpid(pid, 0)
      $?.exitstatus == 0
    end
  rescue Timeout::Error
    Process.kill(15, -Process.getpgid(pid))
    false
  end
end

这也允许您跟踪进程状态

也许这将帮助其他人实现类似的超时功能,但需要从shell命令收集输出。

我已经调整了@shurikk的方法来与Ruby 2.0和Fork子进程的一些代码一起工作,超时并捕获输出以收集输出。

def exec_with_timeout(cmd, timeout)
  begin
    # stdout, stderr pipes
    rout, wout = IO.pipe
    rerr, werr = IO.pipe
    stdout, stderr = nil
    pid = Process.spawn(cmd, pgroup: true, :out => wout, :err => werr)
    Timeout.timeout(timeout) do
      Process.waitpid(pid)
      # close write ends so we can read from them
      wout.close
      werr.close
      stdout = rout.readlines.join
      stderr = rerr.readlines.join
    end
  rescue Timeout::Error
    Process.kill(-9, pid)
    Process.detach(pid)
  ensure
    wout.close unless wout.closed?
    werr.close unless werr.closed?
    # dispose the read ends of the pipes
    rout.close
    rerr.close
  end
  stdout
 end

处理进程、信号和计时器不是很容易。这就是为什么您可以考虑委托这个任务:在新版本的Linux上使用命令timeout:

timeout --kill-after=5s 10s my_bash_command -c12 -o text.txt

相关内容

  • 没有找到相关文章