Unix Signal Processing in Ruby

In this article, we will see how to handle Unix signals in Ruby. For a good discussion on the basics I recommend the book Working With Unix Processes by Jesse Storimer. Create test.rb file with:

p Process.pid

loop { p 'running... ' }

In a IRB terminal, run:

Process.kill(:QUIT, <process id of test.rb goes here>)

This will not make the test.rb process to quit. We need to trap the :QUIT signal and exit with appropriate status code.

p Process.pid

Signal.trap(:QUIT) do 
  p 'Exiting gracefully'
  exit(0) 
end

loop { p 'running... ' }

This will make the test.rb process to quit. To send any Unix signal, you use the same method kill. It may be counter-intuitive. Ideally, I would expect a signal method. Anyways, what happens if you catch Exception?

p Process.pid

begin
  loop do 
    sleep 1
    p 'running... ' 
  end
rescue Exception => e
  p e.message
  p "Catching all exceptions like this is not a good practice"
end

If you don't trap the QUIT signal, it is caught by the generic Exception as SIGQUIT.


Related Articles