等待Ruby子pid退出

我正在尝试分叉一个子进程,等待它完成,如果它在一定时间内没有完成,就把它杀掉。

这是我到目前为止:

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的新手。 我的代码实际上是forking工作,但我只是不知道如何处理它的等待/查杀方面。

使用Timeout模块 :(来自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 

给一个subexec的机会。 来自README:

Subexec是一个简单的库,它使用可选的timeout参数生成外部命令。 它依赖于Ruby 1.9的Process.spawn方法。 此外,它适用于同步和异步代码。

对于作为CLI的Ruby包装器的库很有用。 例如,使用ImageMagick的mogrify命令调整图像大小有时会停止并且永远不会将控制权返回到原始进程。 输入Subexec。