Unix File Locks

David Beckemeyer david at bdt.UUCP
Thu Apr 6 02:58:26 AEST 1989


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?

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

Excuse me if this has come up thousands of times before; I've never seen it.
-- 
David Beckemeyer (david at bdt.UUCP)	| "Adios amigos.  And, as they say when 
Beckemeyer Development Tools		| the boys are scratching the bad ones,
478 Santa Clara Ave. Oakland, CA 94610	| 'Stay a long time, Cowboy!'"
UUCP: {uunet,ucbvax}!unisoft!bdt!david	|                  - Jo Mora



More information about the Comp.unix.wizards mailing list