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

Hi Perl monks. I have a large program with many different packages. Some of the packages use voluntary file locks, that are normally cleaned out in the END block. But, when a SIGINT is sent, the END block doesn't get seen. So I had the idea to "chain" signal handlers on SIGINT:

# Use a closure to add a new behavior to the # chain of behavior for the interupt handler { my $OldINTHandler = $SIG{'INT'}; defined $OldINTHandler or $OldINTHandler = sub { exit(2); }; sub NewIntHandler { unlink(@LockFileArray); &{$OldINTHandler}; } # Install the new handler $SIG{'INT'} = \&NewIntHandler; }


The idea here is to preserve any existing behavior but still unlink my file locks in the case of a SIGINT. I think that me implementation is solid can be used throughout. However, signal handlers can have unexpected behavior -- and I would really like to hear what might go wrong with this approach. (Assuming the chaining method is used throughout - ie, $SIG{'INT'} isn't stupidly set to a non-chaining handler.)

One point of concern -- I couldn't find a code reference to the default handler, so I had to put an 'exit' in explicitly. Maybe you know a better way?

BTW - I know there are many more signals.. at most I would catch SIGTERM too, so 'kill' would work in a nice way.

Thanks for your help!

Replies are listed 'Best First'.
Re: Chaining Signal Handlers
by ikegami (Patriarch) on Aug 02, 2007 at 21:37 UTC

    Why not just do

    @SIG{qw( INT TERM )} = sub { exit(2); }

    That will call your END blocks.