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'

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

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

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

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.