プロセスが機能していることをテストしたいので、以下を実行します。
cmd = "my unix command"
results = `#{cmd}`
コマンドにタイムアウトを追加して、x秒以上かかる場合に、コマンドが機能していないと見なすにはどうすればよいですか?
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 # ""
それをスレッドに入れ、別のスレッドを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の方が優れています:)これはローテクルートです。
スレッドを使用したはるかに簡単な方法:
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