2012-06-05 4 views

답변

7

루비는 Timeout module과 함께 출시됩니다. 스레드

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

당신이 필요로하는 경우 (즉 좀비를 청소) 프로세스 테이블을 정리하는 타임 아웃이 발생했을 때 무언가를하려면'Timeout :: Error'를 구하십시오. –

+0

예. 나는 그것을 언급 했어야했다. – steenslag

+1

쉘 프로세스가 타임 아웃 블록 안에서 시작하면 죽이는 지 확인하십시오. 왜냐하면 계속 실행되기 때문입니다. http://stackoverflow.com/questions/8292031/ruby-timeouts-and-system-commands를 참조하십시오. –

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 's는 더 좋지만 :) 이것은 최첨단 경로입니다.

0

훨씬 간단한 방법 : 자식 프로세스는 sudo를 사용하는 경우 이전의 답변에

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 
0

한 가지주의해야 할 점은, 당신은 아이를 죽일 수 없어, 당신은 좀비 프로세스를 생성합니다.

당신은 정기적으로 프로세스를 실행해야합니다

::는 waitpid (-1, 프로세스 :: WNOHANG) 아이들의 종료 상태를 수집하고

관련 문제