lockfile-progs

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 :

  1. It will not break if there is a stale lock file around
  2. I can loop retrying to gain a lock, if necessary, with minor effort
  3. 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

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
We don't take kindly to automated nonsensible adverts around here.