说我有一个像下面这样的函数,如何捕获Process.spawn调用的输出?如果超过指定的超时时间,我也应该能够终止进程。Fork子进程超时和捕获输出
请注意,该功能还必须是跨平台的(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
谢谢。
完美!正是我所追求的,比我的解决方案更优雅:) – thegreendroid
'_,'在这段代码中意味着什么? –
@TamerShlash读取'Process.wait2'文档,它返回一个元组(两个值),我们将其中一个赋给'status',另一个(第一个)赋给_,这是您想要丢弃时的惯例一个值。 –