I have a perl script (modified from one of Chris Nandor's) that I run as a background-process/daemon via fork(). Now I know I can use kill to end it, but I was wondering if there was a way that I can catch the SIGTERM to do one last thing before quitting?
You just need to install a TERM handler routine in the child process. Eg:
$pid = fork;
if ($pid) {
# parent process prints message and exits
print "Running background process ($pid)\n";
exit;
}
else
{
# child process installs handler then sits in a loop
$SIG{TERM} = \&cleanup;
while (1)
{
}
} sub cleanup {
print "Hello, World!\n";
exit 0;
}You should get the following:
./foo.pl
Running background process (15117)
~% kill 15117
~% Hello, WorldNeil
