Shell - lockfiles

Lockfiles - learned this from a colleague - use symlinks. One one winner for creating a symlink

#!/bin/bash

# test out lock files
# should withstand: kill (all signmals), and most races

me=$(basename $0)
lockfile=/tmp/$me.lock

# primitive locking - use symlinks that point to pid
if [[ -L $lockfile ]]
then

    # still running or remove dead lock
    # could race here
    grep $me /proc/$(readlink $lockfile)/cmdline &&
        exit || rm $lockfile

fi

# create lock - exit if we lose
# if we get the link, we win.
ln -s $$ $lockfile || exit

# cleanup except signal 9 (handled in readlink check)
trap "rm $lockfile" 0

# do stuff

Published on in