2012-03-16 16 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

相关问题