2017-04-21 136 views
-2

我有一個包含IO.popen調用的Ruby腳本。我可以用CTRL + C取消popen呼叫(我使用Signal.trap("SIGINT"),然後導致我呼叫kill -2 #{popen_pid})。這工作正常,當我按CTRL + C時,kill -2導致popen進程在結束自身之前運行一些清理。如何在Ruby中模擬Ctrl + C?

我的問題:我也想在popen過程花費太長時間時能夠有相同的行爲。但是,我無法模仿CTRL + C行爲。在ruby腳本的pid上使用Process.kill最終會在沒有發生清理的情況下結束所有事情,並且在popen進程上運行Process.kill什麼也不做。我試着用反引號直接訪問shell,在ruby腳本的pid和popen pid上調用kill -2,但那些都沒有做任何事情。

有沒有人有任何建議?

回答

0

原來,我也陷入了問題,主要是因爲我想打印器一起生產線,因爲他們發生的事情,也有超時,會做一個kill -2鼓勵加工清理。

最後,我結束了開始一個新的線程旁邊的POPEN通話(但在此之前,我開始打印的命令的東西),那裏的線程將調用kill -2一旦POPEN電話比我的等待時間需要較長的時間:

Thread.new do 
    $next_thread += 1 
    this_thread = $next_thread - 1 
    $active_threads[this_thread] = true 
    start_time = Time.now 
    while true 
    break if not $active_threads[this_thread] 
    minutes_elapsed = (Time.now - start_time)/60 
    if minutes_elapsed > 90 
     inner_packer_pid = `ps -Af | tr -s ' ' | grep -v "grep" | grep "packer build" | cut -d' ' -f2 | sort | tail -n 1`.strip() 
     `kill -2 #{inner_packer_pid}` 
     cancel_build() 
     break 
    end 
    end 
    $active_threads[this_thread] = false 
end 

builders = Set.new 

packer_build = IO.popen("packer build -color=#{not $is_no_color} #{spec_file} 2>&1") 
$packer_build_pid = packer_build.pid 
packer_build.each do |line| 
    puts line 
end 
0

可能很難得到有關殺死進程的答案,特別是在訪問shell時。一個平臺上的解決方案可能無法在其他平臺上運行。而不是試圖通過殺死你的流程的麻煩,我會建議使用超時,如果你的IO.popen調用需要比你想要的更長的時間,那麼你可以做你的清理救援。

require 'timeout' 

seconds_to_wait = 10 


begin 
    block_result = Timeout.timeout(seconds_to_wait) do 
    # your IO stuff 
    end 
rescue Timeout::Error 
    puts "Ain't nobody got time for that!" 
    # do your clean up here 
end 
+0

這工作在停止popen呼叫,但它本質上用-9信號調用它。我需要-2,因爲進程需要運行一些內部清理... – ldanielw1