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
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.)
-Kyle