A Linux Shell Script With An Effective Locking Mechanism Using /proc

Sat 14 January 2012

I recently had to write a Bash shell script that had locking capabilities, and I couldn’t find any decent examples online that would do the trick. My colleague Laurie showed me this example that works pretty well. There are a few issues with using locks that, if the script is not carefully written, can come up:

  • If the script dies before it can delete the lock file, you’ll want to delete the lock file when the script runs again. So you’ll want to write a value in the lock to know if the process is running, and using the process ID is the safe bet..
  • But you have to make sure that the PID isn’t some other process that happened to get the PID since the last crash. So you can check /proc and make sure that the process really is your script.

Below is the code:


# Locking mechanism

#Look for existing lock files
PIDFILES=`ls $PIDFILE_BASE* 2&> /dev/null`

if [ -n "$PIDFILES" ] ; then
    # Found existing lock file
    for P in $PIDFILES ; do
        # Get the PID
        PID=`cat $P`
        if [ -f /proc/$PID/cmdline ] ; then
            CMD=`cat /proc/$PID/cmdline`
            if [ "${CMD//$BASENAME}" != "$CMD" ] ; then
                # Lock file exists, exit script
                exit 1
                # Found a bogus PID, deleting it
                rm -f $P
            # Found a dead PID, deleting it
            rm -f $P

echo $$ > $PIDFILE

# Do whatever it is you need to do here...

# Remove the lock file
rm -f $PIDFILE

exit 0