[comp.unix.questions] Lock Files From Shell Scripts

dg@lakart.UUCP (David Goodenough) (11/09/89)

mercer@ncrcce.StPaul.NCR.COM (Dan Mercer) sez:
> ..... Then I considered using ln,  thinking an error
> condition would be returned if the file existed.  But no,  the file
> was overwritten unconditionally.

Humm - sounds like SYSV and a funky ln. However, if mkdir will overwrite
an already existing directory then I'd say you have a really badly broken
system. So why not:

--- cut here --- cut here --- cut here --- cut here --- cut here ---
lock=/tmp/lock

until mkdir $lock 2>&1 >/dev/null
do
    sleep 10
done

# critical stuff

# clean up the lock directory
rmdir $lock

exit 0
--- cut here --- cut here --- cut here --- cut here --- cut here ---

You could also use umask and touch, except touch doesn't return an error
status, at least BSD touch doesn't (again, if mkdir doesn't you're in
dead trouble anyway)
-- 
	dg@lakart.UUCP - David Goodenough		+---+
						IHS	| +-+-+
	....... !harvard!xait!lakart!dg			+-+-+ |
AKA:	dg%lakart.uucp@xait.xerox.com			  +---+

lee@sq.sq.com (Liam R. E. Quin) (11/10/89)

In article <25561EFF.29662@ateng.com> chip@ateng.com (Chip Salzenberg) writes:
>BZZT!  You lose the System V Sweepstakes.
>
>SysV's "ln" will remove an existing file, rather like "cp" will.  You have
>to write your own "link" program.  Those nice C News people did just that.

True.
This is why mkdir can be better...

In my mail to the original poster, I suggested using mkdir in a loop.
A file in the directory can contain the process' PID, and you can then
do simple collision detection, using kill -0 to see if the other process
is running.
Obviously a file containing the Process ID can't be used as a semaphore,
but the directory suffices, because only the process that created the
directory can put the file there.
It is harder to recover from the case of an empty directory, though.

On the whole, it is probably simplest to write a "makelock" program,
but one can't always do that (e.g. no C compiler).

Lee
--
Liam R. Quin, Unixsys (UK) Ltd
lee@sq.com (whilst visiting Toronto from England)
lee@anduk.co.uk (after Christmas)