Skip to content

Instantly share code, notes, and snippets.

@niquepa
Forked from sauloperez/signal_catching.rb
Created March 8, 2017 19:25
Show Gist options
  • Save niquepa/5838af288cd05ffaf3701a35192c9fe8 to your computer and use it in GitHub Desktop.
Save niquepa/5838af288cd05ffaf3701a35192c9fe8 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
}
@niquepa
Copy link
Author

niquepa commented Mar 8, 2017

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