ruby – 带有超时和捕获输出的叉子进程
发布时间:2020-12-16 23:00:24 所属栏目:百科 来源:网络整理
导读:说我有一个如下的功能,如何捕获Process.spawn调用的输出?如果超过指定的超时时间,我也应该能够杀死进程. 请注意,该功能也必须是跨平台的(Windows / Linux). def execute_with_timeout!(command) begin pid = Process.spawn(command) # How do I capture out
说我有一个如下的功能,如何捕获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:我把超时实现作为你的家庭作业;-) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |