4

プロセスが機能していることをテストしたいので、以下を実行します。

cmd = "my unix command"
results = `#{cmd}`

コマンドにタイムアウトを追加して、x秒以上かかる場合に、コマンドが機能していないと見なすにはどうすればよいですか?

4

4 に答える 4

7

Ruby にはTimeout モジュールが同梱されています。

require 'timeout'
res = ""
status = Timeout::timeout(5) {res = `#{cmd}`} rescue Timeout::Error

# a bit of experimenting:

res = nil
status = Timeout::timeout(1) {res = `sleep 2`} rescue Timeout::Error 
p res    # nil
p status # Timeout::Error

res = nil
status = Timeout::timeout(3) {res = `sleep 2`} rescue Timeout::Error 
p res    # ""
p status # ""
于 2012-06-05T19:00:15.357 に答える
1

それをスレッドに入れ、別のスレッドをx秒間スリープさせてから、まだ完了していない場合は最初のスレッドを強制終了します。

process_thread = Thread.new do
  `sleep 6` # the command you want to run
end

timeout_thread = Thread.new do
  sleep 4   # the timeout
  if process_thread.alive?
    process_thread.kill
    $stderr.puts "Timeout"
  end
end

process_thread.join
timeout_thread.kill

ただし、steenslagの方が優れています:)これはローテクルートです。

于 2012-06-05T18:54:45.993 に答える
0

スレッドを使用したはるかに簡単な方法:

p = Thread.new{ 
   #exec here
}
if p.join( period_in_seconds ).nil? then
   #here thread p is still working
   p.kill
else
   #here thread p completed before 'period_in_seconds' 
end
于 2016-10-14T13:25:04.700 に答える