ruby timeouts and system commands

前端 未结 4 1855
傲寒
傲寒 2020-12-09 16:13

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 th

4条回答
  •  -上瘾入骨i
    2020-12-09 16:50

    in order to properly stop spawned process tree (not just the parent process) one should consider something like this:

    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
    

    this also allows you to track process status

提交回复
热议问题