lockfile-progs
Submitted by David Goodwin on Tue, 08/05/2007 - 11:56.
Lockfile-progs
Normally when writing a shell script and not wanting more than one of 'it' to run at a time, I use something like :
LOCK=/tmp/something
if [ -f $LOCK ]; then
# lock file already exists....
exit 1
fi
trap "/bin/rm $LOCK" EXIT SIGKILL SIGTERM SIGQUIT
touch $LOCK
# rest of script here
The other day, I went to create yet-another-script and this time stumbled onto lockfile-progs, in which case my locking algorithm can be slightly more elegant like :
LOCKFILE=/tmp/var-mail-vmail-backup.lock
lockfile-create --retry 1 $LOCKFILE
if [ $? -ne 0 ]; then
# could not create lock
exit 2
fi
lockfile-touch $LOCKFILE &
LOCKFILEPID="$!"
# rest of script here
kill $LOCKFILEPID
lockfile-remove $LOCKFILE
I think I prefer the lockfile-progs approach, as :
- It will not break if there is a stale lock file around
- I can loop retrying to gain a lock, if necessary, with minor effort
- It's probably not vulnerable to any sort of timing based 'attack'
However, I'm not keen on the extra stuff to go at the end of the script, and I at least feel happier with my original approach that however the script exits, the lockfile will get removed.
Combining both approaches seems to be a good idea, with something like the following being the result :
LOCKFILE=/tmp/var-mail-vmail-backup.lock
lockfile-create --retry 1 $LOCKFILE
if [ $? -ne 0 ]; then
# could not create lock
exit 2
fi
lockfile-touch $LOCKFILE &
LOCKFILEPID="$!"
trap "kill $LOCKFILEPID ; lockfile-remove $LOCKFILE" EXIT SIGKILL SIGTERM SIGQUIT
# rest of script here
Thoughts/comments welcome...
Technorati Tags:
Post new comment