Creating a lock file in csh?

Robert Hartman rhartman at thestepchild.sgi.com
Wed Apr 17 03:53:47 AEST 1991


In article <1991Apr15.205654.26253 at unhd.unh.edu> al at unhd.unh.edu (Anthony Lapadula) writes:
>I'll soon be writing a script (most likely in csh) that has at least
>one critical section ...
>
>I had thought that creating a lock file -- and checking for its presence
>when starting up -- would be a reasonable way to solve the problem.
>
>-- Anthony (uunet!unhd!al, al at cs.unh.edu) Lapadula

Seems to me you could make this work in csh as follows:

	set noclobber
	(echo "${user}: $$ `date`" > $file.lock) >& /dev/null
	if ($status == 0) then
	    if ($$ == "`awk '{ print $2 }' $file.lock`") then
        	# enter critical section
        	# ...
	        # exit critical section
	    else
	        echo "$file in use by `cat $file.lock`"
	        exit 1
	    endif
	else
	    echo "$file in use by `cat $file.lock`"
	    exit 1
	endif
	unset noclobber

Noclobber insures that if the file exists your attempt to overwrite it
wil fail.  The redirect to /dev/null is a standard way to peel off the
standard error message (the "else" statements are more meaningful).  I
suppose that there are more efficient comparisons than ($status == 0),
but that one is quite clear.  The nested if double-checks to make sure
that the current process actually holds the lock.  This is probably
overkill, but it's easy enough to comment out or delete.

Can't see how NFS could matter here.

-r



More information about the Comp.unix.shell mailing list