goelweb.com --> Software --> Unix utilities --> Simple Mutual Exclusion
Sometimes I want only one instance of a process to run. If another instance of that process starts, we want to make sure that this second process does not run until the first instance completes. Here's boilerplate code for simple mutual exclusion.
$ cat mutex.sh
#/bin/sh
## Make sure that you set UNIQUE_NAME to be
## unique for each process you want to be
## mutally exclusive
UNIQUE_NAME=zzdewdzz
LOCK_FILE="/tmp/flock_${UNIQUE_NAME}"
## if lock file does not exist, create lock file
test ! -f $LOCK_FILE && touch $LOCK_FILE
## YOU HAVE TWO OPTIONS:
## 1) exit
## 2) sleep for a random period of time
## maybe the first process will complete
## by the time we're done sleeping
## this is the strategy we've taken
## in this example
## if lock file already existed, sleep for random period of time
if [ $? -ne 0 ]
then
MIN_WAIT_TIME=20 # minimum amount of time to sleep
MOD_WAIT_TIME=30 # value to modulo $RANDOM
SLEEP_TIME=$(( $RANDOM '%' $MOD_WAIT_TIME '+' $MIN_WAIT_TIME ))
sleep $SLEEP_TIME
## test to see if the lock file is still there
test ! -f $LOCK_FILE && touch $LOCK_FILE
## the lock file still exists (another
## process is still running), so exit
if [ $? -ne 0 ]
then
exit
fi
fi
################################
################################
Our code goes here
################################
################################
# delete the LOCK FILE
rm $LOCK_FILE
rishi.goel@alumni.usc.edu