Unix File Locks

Chris Torek chris at mimsy.UUCP
Thu Apr 6 17:29:08 AEST 1989


In article <538 at bdt.UUCP> david at bdt.UUCP (David Beckemeyer) writes:
>For years I've seen a lot of Unix code that uses "lockfiles".  It is
>often of the form:
>
>	if (stat(lockpath, &statbuf) == 0) 
>		return(-1);	/* lock failed */	
>	if ((lock_fd = creat(lockpath, 0600)) < 0)
>		return(-1);	/* error */
>	/* lock succeeded */
>
>My question is:  Isn't there a race condition between the stat and creat?

Yes.

>I've seen this type of code all over the place and I've never understood
>why it works.

For the same reason that code without locks `works': actual conflicts are
rare.

Two better mechanisms, which still leave dead locks behind in the
presence of system crashes (including power failures and the like),
are

	if ((lock_fd = open(lockpath, O_CREAT|O_EXCL, 0666)) < 0)
		... failed ...
	else
		... succeeded ...

and

	if (link(temppath, lockpath) < 0)
		... failed ...
	else
		... succeeded ...

A combination of either of these and advisory locks (file locks in
4BSD or byte-span locks in Other Leading Brands) works best.  (Pure
advisory locks allow anyone who can open the file to lock it, permanently.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.wizards mailing list