Reputation: 304
I have a small Perl daemon that I'm refactoring and I have a best practice question.
The daemon writes out a pid file when it starts up and should remove it when it shuts down.
Would you recommend putting the pid file deletion code in a signal handler like this:
$SIG{__DIE__} = \&cleanup;
or should I put that code in an END{}
block?
Upvotes: 3
Views: 301
Reputation: 2953
SigDie is only recommended for debug purposes, stick to END, and DESTROY blocks. Part of the reason as that SigDie may be overridden, sometimes unexpectedly by an included library or sub, where as multiple END blocks will all get executed in reverse order.
Here's an example of the problems you may encounter;
#!/usr/bin/env perl
use strict;
use warnings;
$SIG{__DIE__} = sub { print("SIG:Foo\n"); };
END { print("END:Foo\n"); }
Foo::do();
die "Something went wrong";
package Foo;
sub do {
# do something useful, but oops forgot
# to remove my debug SIG...
$SIG{__DIE__} = sub { print("SIG:Bar\n"); };
}
END { print("END:Bar\n"); }
__END__
## Example Output, note no SIG:Foo
SIG:Bar
Died at test-end.pl line 10.
END:Bar
END:Foo
Upvotes: 4