Skip to content

Instantly share code, notes, and snippets.

@sauloperez
Last active November 11, 2020 11:25
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save sauloperez/6592971 to your computer and use it in GitHub Desktop.
Save sauloperez/6592971 to your computer and use it in GitHub Desktop.
How to catch SIGINT and SIGTERM signals in Ruby
# Signal catching
def shut_down
puts "\nShutting down gracefully..."
sleep 1
end
puts "I have PID #{Process.pid}"
# Trap ^C
Signal.trap("INT") {
shut_down
exit
}
# Trap `Kill `
Signal.trap("TERM") {
shut_down
exit
}
@Neonit
Copy link

Neonit commented Jul 24, 2016

Really cool. You can utilize Ruby's catch-throw, if you want to trap the signal and just continue, as if you have rescued it.

Signal.trap('INT') { throw :sigint }

catch :sigint
    do_stuff_that_may_be_interrupted
end
puts 'Just caught a SIGINT'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment