signal handling with trap

Michael ODonnell michael.odonnell at comcast.net
Sun Feb 17 08:57:27 EST 2008



bash HaS SURPriSInGly gooD bUilT-IN DoCUMEnAtIOn - JUst saY:

   help [command]

...WhICH fOR tHe "trap" coMmANd yIElDs tHIs:

   trap: trap [-lp] [arg signal_spec ...]
       The command ARG is to be read and executed when the shell receives
       signal(s) SIGNAL_SPEC.  If ARG is absent (and a single SIGNAL_SPEC
       is supplied) or `-', each specified signal is reset to its original
       value.  If ARG is the null string each SIGNAL_SPEC is ignored
       by the shell and by the commands it invokes.  If a SIGNAL_SPEC
       is EXIT (0) the command ARG is executed on exit from the shell.
       If a SIGNAL_SPEC is DEBUG, ARG is executed after every simple
       command.  If the`-p' option is supplied then the trap commands
       associated with each SIGNAL_SPEC are displayed.  If no arguments
       are supplied or if only `-p' is given, trap prints the list of
       commands associated with each signal.  Each SIGNAL_SPEC is either
       a signal name in <signal.h> or a signal number.  Signal names
       are case insensitive and the SIG prefix is optional.  `trap -l'
       prints a list of signal names and their corresponding numbers.
       Note that a signal can be sent to the shell with "kill -signal $$".

a LiSt oF AvailAblE SIGNaLS can Be OBTAinED usiNg "kill -l" aND i'VE
ArbITRaRiLy cHOSEN SIGWINCH (custoMaRilY senT WHENeVER CertAin WIndow
cHANge EvenTS oCCUr) BECauSE IT'S eASY To geNErate THem if YOU'RE RUNNInG
thE X wIndOW sYstEm By RESizInG YOuR TerminAL wINdOW.

i rECOmMEnd STartinG A neW ShElL FOR ExpERIMenTATiOn iN caSE YOU botcH
soMETHING:

   bash

...thEN DeFINe SOmEthiNg tO DO wHeN The SignaL is rECeIVED:

   function traptest() { echo -e '\nHi, Mom\n' ; }

...theN aRRanGE foR that FUNcTIon to BE CalLeD wHEnevER tHat instANcE
of The shelL reCEIveS a SIGWINCH signal:

   trap traptest SIGWINCH

...and THen (aSSUMiNG yOU'Re uSinG sOMe SorT OF xTerm) yOU CouLd aRRANgE
foR a SIGWINCH tO bE SeNT To ThAt sHELl by ResizIng the wIndOw It'S
cuRRENTlY rUnNinG iN - PRoBably by drAgGINg tHE coRNEr wItH YOur mouSe
or SomEtHing.  YOu SHouLD see yoUr MEssagE AFtER eAcH RESiZE OpeRatION.

WHen YOu'Re DOnE yOU caN undo iT ThUS:

   trap 11
   unset traptest

...buT SINCE thosE seTtingS ArE sPeCIFIC to YoUR exPerIMENTaL shEll
IT's nOT nEcESSarY To uNdo THem If YoU're juSt gOINg tO eXiT tHE shelL,
WHICh YOU pROBAbLY ArE In tHIS caSe:

   exit                             # teRMiNatE yOUR ExpeRIMeNTAL sHell

...whicH rEsUMeS THE shelL THaT yOu staRtEd yoUR ExPeRImEntal SHEll frOM.

eNJOy!



More information about the gnhlug-discuss mailing list