The Musings of Chris Samuel

The Musings of Chris Samuel

The Thoughts and Feelings of a Melbourne Person

The Musings of Chris Samuel RSS Feed
 
 
 
 

Exclusive locks in Bourne shell scripts

Been writing some stuff in shell that needs to be able to ensure it doesn’t start itself twice, so a bit of Googling for exclusive locks in shell scripts brought me to this page on “advanced shell scripting” which had something that looked good.

Problem is that when you put it into a script you’ll find it doesn’t actually work because of some trivial coding issues.

So here’s the fixed version of that function..

# Function to do atomic locking.
# Original found at http://members.toast.net/art.ross/rute/node24.html
# Fixed by Chris Samuel http://www.csamuel.org/

function my_lockfile ()
 {
         TEMPFILE="$1.$$"
         LOCKFILE="$1.lock"
         ( echo $$ > $TEMPFILE ) >& /dev/null || (
                 echo "You don't have permission to access `dirname $TEMPFILE`"
                 return 1
         )
         ln $TEMPFILE $LOCKFILE >& /dev/null && {
                 rm -f $TEMPFILE
                 return 0
         }
         kill -0 `cat $LOCKFILE` >& /dev/null && {
                 rm -f $TEMPFILE
                 return 1
         }
         echo "Removing stale lock file"
         rm -f $LOCKFILE
         ln $TEMPFILE $LOCKFILE >& /dev/null && {
                 rm -f $TEMPFILE
                 return 0
         }
         rm -f $TEMPFILE
         return 1
 }

RSS 2.0 feed • Leave a response, or trackback

Leave a Reply

Related Posts

Music

Spam Blocked

RSS ABC News

Blogroll

People

Sites

Recent Posts

Random Image

 
2005-12-05-14:54_048.JPG
 

Categories

Archives

Meta

Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Australia
Creative Commons Attribution-NonCommercial-ShareAlike 2.5 Australia