bash : locking issues – example with setlock

Something that kept me busy for a while. An internal (bash) framework sometimes (Isn’t that great! -sigh-) gave unexpected results. Sometimes the timings were too long, and sometimes data was missing. In the end, it was due to a locking issue. A program tried to execute something while forcing an internal lock. Yet the program was waiting until the lock was released. But when in some cases when two programs do this, this causes a deadlock.

The code below is a way to get around this deadlock. It’s an example using “setlock”, yet it shows the concept. Instead of waiting for the program to release the lock (default behaviour with “setlock”), you can script a small loop that comes back after a few seconds. Yet you have to setup the locking mechanism in a manner that it won’t wait for the lock (option -n for “setlock”).

SUME="bash -c "
SETLOCK="path-to-setlock"
EXECUTE="your-script"
PARAMETERS="your-parameters"
ID="your-unique-id-for-locking"
# usage of a control structure with non-wait locking
# this is done to avoid locking issues ^^
var0=0
LIMIT=3
SNOOZE=5
while [ "$var0" -lt "$LIMIT" ]
do
  var0=`expr $var0 + 1`
  eval $SUME "$SETLOCK -n $TMPDIR/lock_$ID $EXECUTE $PARAMETERS 2>/dev/null "  2>/dev/null
  EC=$?
  if [ $EC -eq 0 ] ; then
     var0=`expr $LIMIT + 1`
  else 
     sleep $SNOOZE
  fi
done
exit $EC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.