Creating a lock file in sh?

Simon J Gerraty sjg at melb.bull.oz.au
Fri Apr 26 12:59:21 AEST 1991


In <1991Apr17.201931.14536 at odin.corp.sgi.com> rhartman at thestepchild.sgi.com (Robert Hartman) writes:
>In article <PABLO.91Apr17110430 at tofu-hut.csd.sgi.com> pablo at sgi.com (Pablo Sanchez) writes:
>>Hey there,
>>
>>    I apologize if this has been hashed over a bizzillion times but can
>>someone please send me their Bourne-shell lock-file implementation.
>>Thanks.

>Aside from the fact that it isn't guaranteed over NFS, you can get some
>measure of protection this way:

>	if [ ! -w $file.lock ] ; then
>		echo $user: $$ `date` > $file.lock
> [stuff deleted]

generally speaking I think you'd have far fewer problems using
mkdir.

Nearly? all file related lock mechanisms will fail if used by
root.  mkdir on the other hand is guaranteed to fail if the
directory exists.

Here is the lock section from my addusr script I hope you get
the idea (this would also work over NFS):

lock_pw()
{
  if [ "$pw_lock" = "no" ]; then
    if [ ! -w $PASSWD ]; then
	echo "Sorry, must be able to write \"${PASSWD}\""
	exit 1
    fi
    if mkdir ${PW_LOCK}; then
	pw_lock=me
    else
	echo "Sorry, \"${PASSWD}\" is busy.  Try again later"
	exit 2
    fi
  fi
}

unlock_pw()
{
  if [ "$pw_lock" = "me" ]; then
	rmdir ${PW_LOCK}
	pw_lock=no
  fi
}


-- 
Simon J. Gerraty		<sjg at melb.bull.oz.au>

#include <disclaimer,_witty_comment>



More information about the Comp.unix.shell mailing list