|
Catch Kill Signals In Perl
|
|
|
|
|
Contributed by Chad Brandt
|
|
|
|
Saturday, 03 July 2004
When you create a perl program that will run in the background as a deamon, it is a good idea to catch kill signals and do cleanup processing in your program before it exits. Perl has a sigtrap function that make this very easy to do.The following example shows a perl program running as a deamon that prints messages when a signal is sent to it. This demonstrates how you can catch signals and do the neccassary processing
#!/usr/bin/perl ############################################################ # This is a sample program that shows how you can catch # signals to your program when running as a deamon # ############################################################
use sigtrap 'handler' => \&reload, 'HUP'; use sigtrap 'handler' => \&cleanAndExit, 'INT', 'ABRT', 'QUIT', 'TERM';
# create the deamon / kill parent if (fork()){ exit(0); }
print "New PID - $$\n";
for(;;){ # do your deamon work here sleep(1);
}
# refresh the config info and continue processing # this method will be called if the following signal is given to your pid # kill -HUP sub reload() {
print "Caught a HUP signal, reload config files and continue processing\n"; }
# close all file handles and do any other clean up # this method will be called if the followng signals are given to your pid # kill -INT # kill -ABRT # kill -QUIT # kill -TERM sub cleanAndExit(){
print "Caught a kill signal, cleaning up and exiting\n"; exit(1); }
Powered by AkoComment 1.0 beta 2! |