Thursday, March 20, 2008

Playing with Signals in Ruby

What?

Signal trapping and processing in Ruby - it's way easy.

Why?

Signals are very useful, e.g. to detect shutdown and let your program clean up after itself.

How?

Here's a quickie that'll get you started playing.



# Let's see which signals we can trap

{
"ABRT"=>6, "ALRM"=>14, "BUS"=>7,
"CHLD"=>17, "CLD"=>17, "CONT"=>18,
"FPE"=>8, "HUP"=>1, "ILL"=>4,
"INT"=>2, "IO"=>29, "IOT"=>6,
"KILL"=>9, "PIPE"=>13, "PROF"=>27,
"QUIT"=>3, "SEGV"=>11, "STOP"=>19,
"SYS"=>31, "TERM"=>15, "TRAP"=>5,
"TSTP"=>20, "TTIN"=>21, "TTOU"=>22,
"URG"=>23, "USR1"=>10, "USR2"=>12,
"WINCH"=>28, "XCPU"=>24, "XFSZ"=>25
}.each do |signal,num|
puts "Set up trap for #{signal} #{num}"
trap signal do
puts "#{signal} #{num} was trapped"
end
end

# Sleep away and lets press some buttons. Try for example ctr-c
sleep 100


Also check out:


at_exit do
puts "I'm quitting now!"
end


Very useful!

4 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Unknown said...

Thank's for that, I didn't know about signals.

But be careful, you've got a typo in the last code snippet : it's "at_exit" instead of "at_exist"

Joe said...

at_exit?

Marcus Westin said...

Indeed! Thanks for the pointer Stephane and Joe (seperated by 1 minute, two weeks after posting?! Did you coordinate? :)