我正在尝试分叉一个子进程,等待它完成,如果它在一定时间内没有完成,就把它杀掉。
这是我到目前为止所做的:
servers.each do |server|
pid = fork do
puts "Forking #{server}."
output = "doing stuff here"
puts output
end
Process.wait
puts "#{server} child exited, pid = #{pid}"
end
在Process.wait之后的某个地方,我希望某种实用程序等待20秒,如果进程仍然在那里,我想杀死它并将输出标记为“ERROR。”
我是fork / exec的新手。我的代码实际上是分叉的,但我只是不知道如何处理它的等待/查杀方面。
答案 0 :(得分:9)
使用Timeout
module :(来自http://www.whatastruggle.com/timeout-a-subprocess-in-ruby的代码)
require 'timeout'
servers.each do |server|
pid = fork do
puts "Forking #{server}."
output = "doing stuff here"
puts output
end
begin
Timeout.timeout(20) do
Process.wait
end
rescue Timeout::Error
Process.kill 9, pid
# collect status so it doesn't stick around as zombie process
Process.wait pid
end
puts "#{server} child exited, pid = #{pid}"
end
答案 1 :(得分:0)
有机会subexec。来自自述文件:
Subexec是一个简单的库,它使用可选的timeout参数生成外部命令。它依赖于Ruby 1.9的Process.spawn方法。此外,它适用于同步和异步代码。
对于作为CLI的Ruby包装器的库很有用。例如,使用ImageMagick的mogrify命令调整图像大小有时会停止并且永远不会将控制权返回到原始进程。输入Subexec。