Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wasatch!cs.utexas.edu!uunet!auspex!guy From: guy@auspex.auspex.com (Guy Harris) Newsgroups: comp.unix.wizards Subject: Re: Unix File Locks Message-ID: <1397@auspex.auspex.com> Date: 7 Apr 89 06:50:18 GMT References: <538@bdt.UUCP> Reply-To: guy@auspex.auspex.com (Guy Harris) Distribution: na Organization: Auspex Systems, Santa Clara Lines: 34 >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 /* 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.)