Unix File Locks

Guy Harris guy at auspex.auspex.com
Fri Apr 7 16:50:18 AEST 1989


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

If it works, it works because people are lucky and win the race.

A slightly better version is:

	if ((lock_fd = creat(lockpath, 0400)) < 0)
		return(-1);	/* error */

without the "stat".  This creates the file read-only, which means that a
subsequent attempt to "creat" it by anybody but the super-user will
fail, since they won't have write permission.

An even better version is:

	#include <fcntl.h>	/* yes, even on BSD, the documentation */
				/* nonwithstanding.  Trust me. */

	if ((lock_fd = open(lockpath, O_CREAT|O_EXCL|O_WRONLY, 0600)) < 0)
		return(-1);	/* error */

which works on more recent UNIX systems - System III, System V,
4.[23]BSD, and systems derived from one or more of those.  The O_CREAT
makes the "open" create the file if it doesn't exist (subsuming
"creat"); the O_EXCL makes the "open" fail if it *does* exist, even if
you're the super-user.  (The O_WRONLY is a nicer way of saying "leave
the resulting file descriptor open for writing only" than "1" is, these
days.  If you plan to read it, make it O_RDWR instead.)



More information about the Comp.unix.wizards mailing list