Doing some work before exiting (Ruby)

When running a few programs (like Web server or a script), do you notice that sometimes they print out "Good bye" message before exiting? I was wondering if I could do a similar thing in Ruby and it turned out to be pretty easy.

First, I learned that when a process is killed by the system when it receives the signal SIGINT (interrupt) or SIGTERM (terminate). What we should do is to capture these signals and do our actions.

Here is my super simple Ruby script which prints "Shutting down gracefully" message to the console when the program exits

# Signal catching
def shut_down
  puts "\nShutting down gracefully..."
  sleep 1

puts "I have PID #{}"

# Trap ^C
Signal.trap("INT") {

# Trap `Kill `
Signal.trap("TERM") {

sleep 10

Put this code into a file called test.rb and run it with ruby test.rb, you would see the message indicating the program is running. You can press Ctrl + C to exit the program and see the exiting message

I have PID 49854
Shutting down gracefully...

If you want to capture both INT and TERM signal, you can also use at_exit method like this

at_exit do 
  puts "Shutting down gracefully..."

I myself rarely use these but it is helpful to know that they exist. Hope that helps.