3

I am writing a small command-line program in Ruby that looks for changes in a specific folder.

This program repeats a loop every few second to see if there are changes. To stop the program, the user can use Ctrl+C (To send ^C to the console).

Right now, Ruby sends the following stack trace when this happens:

^C./filename.rb:64:in `sleep': Interrupt
from ./filename.rb:64:in `block in parse'
from ./filename.rb:62:in `loop'
from ./filename.rb:62:in `parse'
from ./filename.rb:124:in `<main>'

I would like to change this to show an Exiting now... message, similar to what programs like Rails show when closed in this way.

How can this be done?

Qqwy
  • 5,214
  • 5
  • 42
  • 83

1 Answers1

9

Doing ctrl + c simply sends SIGINT signal to the given ruby process. You can intercept it by rescuing Interrupt:

begin
  loop do
    puts "foo bar baz"
  end
rescue Interrupt
  puts "\nExiting..."
end
vgoff
  • 10,980
  • 3
  • 38
  • 56
ndnenkov
  • 35,425
  • 9
  • 72
  • 104