rubysignalsrescue

Ruby prevent default CTRL+C output ^C


I am catching signal with

rescue Interrupt => e

But it always prints:

^CShutting down!

Is there a way to prevent the default CTRL+C output:

^C

Any ideas?


Solution

  • Some terminals support stty -echoctl to disable echoing of control characters:

    `stty -echoctl`
    
    begin
      loop do
        # ...
      end
    rescue Interrupt => e
      puts 'shutting down'
    end
    

    If the above doesn't work, you can disable all echoing by setting IO#echo= to false:

    require 'io/console'
    
    STDIN.echo = false
    
    begin
      loop do
        # ...
      end
    rescue Interrupt => e
      puts 'shutting down'
    end