Capturing Ctrl-c in ruby

前端 未结 5 1639
慢半拍i
慢半拍i 2020-12-02 06:02

I was passed a long running legacy ruby program, which has numerous occurrences of

begin
  #dosomething
rescue Exception => e
  #halt the exception\'s pr         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 06:31

    If you can wrap your whole program you can do something like the following:

     trap("SIGINT") { throw :ctrl_c }
    
     catch :ctrl_c do
     begin
        sleep(10)
     rescue Exception
        puts "Not printed"
     end
     end
    

    This basically has CtrlC use catch/throw instead of exception handling, so unless the existing code already has a catch :ctrl_c in it, it should be fine.

    Alternatively you can do a trap("SIGINT") { exit! }. exit! exits immediately, it does not raise an exception so the code can't accidentally catch it.

提交回复
热议问题