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

I looked at the perlIpc page about signals, it is very confusing, none of the code forms any addequate example. Can someone give me an example of a script that handles an interrupt signal, and another process that sends it? Thanks

Replies are listed 'Best First'.
Re: signal handling
by dragonchild (Archbishop) on Sep 27, 2001 at 22:50 UTC
    There is a default signal handler for every signal that can be received. Most of them just happen to be NO-OPs.

    To create your own, you have to create a reference to a subroutine and put it into the %SIG array. So, to create your own SIGINT handler, do the following:

    sub my_sig_int_handler { print "Woo-Hoo!\n"; } my $oldSigInt = $SIG{INT}; $SIG{INT} = \&my_sig_int_handler;
    As for sending the signal, I would system out to whatever Unix method you want to use to send the signal. Usually, kill is the most common way I've see. ('man kill' for more details)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: signal handling
by wog (Curate) on Sep 27, 2001 at 23:20 UTC
    Dragonchild is correct about how you setup signal handlers.

    Better then using the UNIX command-line kill command, is using perl's built-in kill function. For example to send the INT signal to the process ID in the $pid variable you could use:

    kill INT => $pid; # which is the same as kill 'INT', $pid;

    Note that people often do something like:

    $SIG{INT} = sub { # code executed on 'INT' signal here }; # <-- that semicolon isn't optional

    ...using an anonymous subroutine instead of a named one.

    Often if one just wants to handle a signal differently for a small section of code one can take advantage of local to temperarily set a signal handler up. For example:

    { my $stop = 0; local $SIG{INT} = sub { $stop++ }; while (!$stop) { # the loop continues until it's left with an explict # last, or until the process recieves SIGINT. } } # our old SIGINT handle is restored here, because we # left the old block.

    (Though you can of course manually store the current signal handler, set a new one, and reset the signal handler when you are done if you want.)

Re: signal handling
by tachyon (Chancellor) on Sep 27, 2001 at 23:54 UTC
    $SIG{INT} = sub { print "You zapped me!\n"; }; print "Try to zap me with ^C, I dare you!\n"; sleep 5; # normally warnings are not fatal warn "This is your last warning\n"; # make warnings fatal $SIG{__WARN__} = sub { print "Died fron the warning @_\n"; exit }; # now warnings will be fatal warn "I warned you!"; print "You will never read this, because the last warning killed me!";

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print