小编典典

带有超时的分叉子进程并捕获输出

linux

说我有一个下面的函数,如何捕获Process.spawn调用的输出?如果花费的时间超过指定的超时时间,我也应该能够终止该过程。

请注意,该功能还必须是跨平台的(Windows / Linux)。

def execute_with_timeout!(command)
  begin
    pid = Process.spawn(command)     # How do I capture output of this process?
    status = Timeout::timeout(5) {
      Process.wait(pid)
    }
  rescue Timeout::Error
    Process.kill('KILL', pid)
  end
end

谢谢。


阅读 392

收藏
2020-06-07

共1个答案

小编典典

您可以使用IO.pipe并告诉Process.spawn使用重定向的输出,而无需外部gem。

当然,仅从Ruby 1.9.2开始(我个人建议1.9.3)

以下是Spinach BDD在内部用于捕获输出和err输出的简单实现:

# stdout, stderr pipes
rout, wout = IO.pipe
rerr, werr = IO.pipe

pid = Process.spawn(command, :out => wout, :err => werr)
_, status = Process.wait2(pid)

# close write ends so we could read them
wout.close
werr.close

@stdout = rout.readlines.join("\n")
@stderr = rerr.readlines.join("\n")

# dispose the read ends of the pipes
rout.close
rerr.close

@last_exit_status = status.exitstatus

原始来源位于features / support /
filesystem.rb中

强烈建议您阅读Ruby自己的Process.spawn文档。

希望这可以帮助。

PS:我将超时实现留给您做功课;-)

2020-06-07