|Welcome to the Monastery|
I have a script that gets called by a daemon. It executes a task that sometimes takes longer than the time between this daemon's scheduled runs. The task is resource intensive enough to where I don't want multiple instances of this script running at once.
To keep this from happening I create a lockfile. If this lockfile is present when the script is run it immediately exits. This file is then deleted at the end of the script.
This setup ran smoothly until recently the system that this script was running on experienced an unscheduled restart. Unfortunately it was in the middle of executing the aforementioned script and a lockfile had been created. The script was forced to stop and the lockfile remained. Curses!
So obviously when the system came back online and the daemon restarted the script stopped being run because the lockfile was permanently created.
What I'd really like to achieve would be a bulletproof lockfile that can withstand this kind of situation. I remembered that File::Temp has an nice UNLINK property that forces the file to be deleted when the process exits. I'm not sure if this happens when the process is killed, however. But that's the sort of functionality that I'm looking for. Also, I don't think you can name the temp files that this module creates.
I looked around on CPAN and found several lockfile modules. It looks like their solution is to add a timer to the lockfile. This doesn't really work for me since this process' runtime can vary quite a bit.
Another solution is to use the PID lockfile and just write a check into the script that checks if that PID currently exists to verify that the lockfile isn't stale. I don't know enough about PID assignment to know how reliable this would be. I was a little surprised that none of the lockfile modules had this check built in.
I could also write a signal handler which would delete my lockfile when a kill signal is received since iirc Perl does not call the END routines when it gets a kill signal.
Long question short - is there a module or a better way of creating reliable lockfiles?