2012-03-16 51 views
1

在我的Ruby腳本中,我調用Perl腳本並等待它完成執行。但是,有時Perl腳本會遇到一系列錯誤,我希望Ruby能夠自動處理這些錯誤。所以,我採取了以下...在執行過程中停止IO.popen,使用異常情況不佳

begin 
    IO.popen(cmdLineExecution) do |stream| 
      stream.each do |line| 
       puts line 
       if line =~ /Some line that I know is an error/ 
       raise MyOwnException 
       end 
      end 
    end 

    begin 
      #Wait on the child process 
      Process.waitpid 
    rescue Errno::ECHILD 
    end 
rescue MyOwnException 
    #Abort the command mid processing, and handle the error 
end 

然而,Perl腳本繼續工作,即使異常被拋出來執行,只知道它是不是管道輸出到STDOUT了。此時,如果我想停止Perl進程,我必須進入任務管理器並手動停止它。然後Process.waitpid結束並從那裏繼續。無論是或者我停止Ruby並且Perl進程繼續在後臺運行,我仍然必須手動停止它。

BTW:這是Windows

所以因此問題是如何阻止IO.popen沒有成爲一個孤兒進程中間過程Perl的進程?

回答

6

所以 - 免責聲明,我使用Ruby 1.8.6和Windows。它是我目前使用的軟件唯一支持的Ruby,因此可能會有更優雅的解決方案。總的來說,在繼續執行之前,最終要確保使用Process.kill命令來終止進程。

IO.popen(cmdLineExecution) do |stream| 
    stream.each do |line|       
     puts line 
     begin 
     #if it finds an error, throws an exception 
     analyzeLine(line) 
     rescue correctionException 
     #if it was able to handle the error 
     puts "Handled the exception successfully" 
     Process.kill("KILL", stream.pid) #stop the system process 
     rescue correctionFailedException => failedEx 
     #not able to handle the error 
     puts "Failed handling the exception" 
     Process.kill("KILL", stream.pid) #stop the system process 
     raise "Was unable to make a known correction to the running enviorment: #{failedEx.message}" 
     end 
    end 
end 

我制定了兩個例外標準類,它們都繼承了Exception

相關問題