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

前端之家收集整理的这篇文章主要介绍了ruby – 带有超时和捕获输出的叉子进程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有一个如下的功能,如何捕获Process.spawn调用输出?如果超过指定的超时时间,我也应该能够杀死进程.

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

@H_301_4@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内部使用的简单实现,用于捕获输出错误输出

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

猜你在找的Ruby相关文章