Skip to content

Instantly share code, notes, and snippets.

@hiremaga
Created March 2, 2010 22:07
Show Gist options
  • Save hiremaga/320008 to your computer and use it in GitHub Desktop.
Save hiremaga/320008 to your computer and use it in GitHub Desktop.
Signal Handling: Ruby vs JRuby
orange:~ $ ruby signal_handling.rb
pid 81402 is sleeping...
^CRuby ensure was run!
Ruby at_exit was run!
signal_handling.rb:34:in `sleep': Interrupt
from signal_handling.rb:34
orange:~ $ jruby signal_handling.rb
pid 81431 is sleeping...
^CJava shutdown hook was run!
orange:~ $ jruby signal_handling.rb emulate_mri_signals
pid 81533 is sleeping...
^CRuby ensure was run!
Ruby at_exit was run!
signal_handling.rb:13: Interrupt (Interrupt)
from :1:in `call'
from :1
Java shutdown hook was run!
orange:~ $
if RUBY_PLATFORM == "java"
if ARGV.include?('emulate_mri_signals')
# Emulate MRI style signal handling: i.e. ensure gets executed and so do any an_exit hooks
trap('SIGTERM') {
raise SignalException, 'SIGTERM'
}
trap('SIGHUP') {
raise SignalException, 'SIGHUP'
}
trap('SIGINT') {
raise Interrupt
}
end
# Java shutdown hook to make sure they're still called with the custom signal handlers
require 'java'
class ShutdownHook
include java.lang.Runnable
def run
puts "Java shutdown hook was run!"
end
end
java.lang.Runtime.getRuntime.addShutdownHook(java.lang.Thread.new(ShutdownHook.new))
end
at_exit {
puts "Ruby at_exit was run!"
}
puts "pid #{$$} is sleeping..."
begin
sleep
ensure
puts "Ruby ensure was run!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment