Shell - lockfiles

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


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

me=$(basename $0)

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

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


# 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