2012-09-24 93 views
5

我試圖分叉一個子進程,等待它完成,如果它沒有在一定的時間內完成,就殺了它。等待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秒,如果這個過程仍然在那裏,我d喜歡殺死它並將輸出標記爲「錯誤」。

我是fork/exec的新手。我的代碼實際上是分叉的,但我不知道如何處理它的等待/查殺方面。

回答

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 
+0

這工作完美! – awojo

0

給個機會subexec。自述文件:

Subexec是一個簡單的庫,它生成一個具有可選超時參數的外部命令。它依賴於Ruby 1.9的Process.spawn方法。此外,它可以與同步和異步代碼一起使用。

對於CLI的Ruby包裝庫很有用。例如,使用ImageMagick的mogrify命令調整圖像大小有時會停頓,並且永遠不會將控制權返回給原始進程。輸入Subexec。