Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I'm working on a script that will be run more or less as a daemon on a linux server. E.g. it will be running in the background any time the machine is powered on. Is it possible for me to allow it to catch some of the standard signals, such as HUP? For instance, if a user does:

bash$ kill -HUP `head /var/run/myscript.pid`

I would like my script to be able to catch that signal and do something accordingly (e.g. re-read it's config files). Anyone know how to do this?

Thanks!

Replies are listed 'Best First'.
Re: Catching Signals in Perl
by sauoq (Abbot) on Sep 04, 2003 at 20:51 UTC
    Is it possible for me to allow it to catch some of the standard signals, such as HUP?

    Sure. You use the special %SIG hash. Read all about it in perlipc.

    Here's a quick demo:

    $ perl -le '$SIG{ HUP } = sub { print "Bye cruel world."; exit }; slee +p 60' &
    Just kill -HUP the resulting process before the minute is up...

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Catching Signals in Perl
by tcf22 (Priest) on Sep 04, 2003 at 20:55 UTC
    Try something like this
    $SIG{HUP} = \&hup_handler; sub hup_handler{ ##Do what you want here }
Re: Catching Signals in Perl
by yosefm (Friar) on Sep 04, 2003 at 20:55 UTC
    like so:

    local $SIG{HUP} = \&hup_handler;

    Now, hup_handler will be called any time sighup is recieved.

    update: Hmm... race condition... and I lost...

    Update: Ok, sauoq, I fixed it like two seconds after my first post, but thanks.

      No such hook: __HUP__

      That should just be "HUP" without underscores.

      -sauoq
      "My two cents aren't worth a dime.";
      
      Special ++ for the local.
Re: Catching Signals in Perl
by naChoZ (Curate) on Sep 05, 2003 at 12:17 UTC