Avoiding race conditions in Bash

I had prototyped the following code for a helper script run as a post-exec routine from rsnapshot:

#!/bin/bash
LOCK=/var/run/rsnapshot.pid
if [ -f $LOCK ]; then
  /bin/ps -p `cat $LOCK` 2>&1 >/dev/null
  if [ $? -eq 0 ]; then
    echo rsnapshot already running
    exit 1
  fi
else
  echo $$ > $LOCK
fi
# main body of script
rm $LOCK
exit 0

This attracted the following feedback, which taught me about the use of bash's -C (toggles noclobber) command and a special use of the trap command.

While that probably works just fine in this case, it's theoretically unsafe as there is a race condition: another rsnapshot could start between the first "if" and the second "echo".
To be safe, lock files should be tested and created atomically, with the same operation. With bash and its relatives it can be done like this:

set -C
if ! echo $$ > $LOCK 2>/dev/null ;then
  set +C
  ...

Also, stale lock removal logic in your script is slightly
off: it leaves the old process id in the lock file instead
of its own.
Finally, it's best to remove the lock file with trap so it won't stay around if the script is interrupted. So, a slightly improved version:

LOCK=/var/run/rsnapshot.pid
set -C
if ! echo $$ > $LOCK 2>/dev/null ;then
  if ps -p $(< $LOCK) 2>&1 >/dev/null
    echo rsnapshot is running
    exit 1
  fi
fi
set +C
trap "rm $LOCK" 0
echo $$ > $LOCK
...

(The seriously paranoid will have noticed there's another race condition in the stale lock removal logic.
Actually getting hit by that one is *really* unlikely, however, and avoiding it gets so complicated that in situations where it is likely to matter I generally recommend not doing it at all - i.e., abort if the lock exists without even trying to check if the other process is still running