假设我有一个如下所示的函数,如何捕获 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
Thanks.
您可以使用IO.pipe
并告诉Process.spawn
使用重定向输出而不需要外部 gem。
当然,只有从Ruby 1.9.2开始(我个人推荐1.9.3)
以下是使用的简单实现菠菜BDD在内部捕获 out 和 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
原始来源位于功能/支持/filesystem.rb
强烈建议您阅读 Ruby 自己的进程.spawn文档。
希望这可以帮助。
PS:我把超时实现作为家庭作业留给了你;-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)