ruby – 带有超时和捕获输出的叉子进程

说我有一个如下的功能,如何捕获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

谢谢.

解决方法

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

当然,只有从Ruby 1.9.2开始(和我个人推荐1.9.3)

以下是Spinach BDD内部使用的简单实现,用于捕获输出和错误输出:

# 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:我把超时实现作为你的家庭作业;-)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...