On Wed, Apr 16, 2008 at 11:10 AM, Kyle McDonald <KMcDonald at egenera.com>
wrote:
> Any advice on a good way to aquire a lock in a shell script?
>
> My first idea is ugly:
>
> > LOCKED="false"
> >
> > while [ "${LOCKED}" = "false" ]; do
> > if [ ! -f /tmp/lockfile ]; then
> > echo $$ > /tmp/lockfile
> > sleep 1
> > # In case 2 proc's both create lockfile at once, verify my pid is in
> the file.
> > if [ `cat /tmp/lockfile` = "$$" ]; then
> > LOCKED="true"
> > fi
> > fi
> > done
> >
> > # do locked stuff here
> >
> > rm /tmp/lockfile
That has problems (what if a malicious person writes your pid to that file?)
> Another suggestion I got was that 'mkdir' is atomic so this might be better:
>
> >
> > while [ ! mkdir /tmp/lockdir ]; do
> > sleep 1
> > done
> >
> > # do locked stuff here
> >
> > rmdir /tmp/lockdir
>
> That is much cleaner. But I"m curious if there are better ideas out
> there. (Short of writing something in C.)
I've used that and have been happy with it. However, mktemp(1) can do
it with files as well.
$ mktemp /tmp/lock
/tmp/lock
$ mktemp /tmp/lock
mktemp: failed to create file: /tmp/lock
--
Mike Gerdts
http://mgerdts.blogspot.com/