Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!ucsd!sdcsvax!ucsdhub!isg100!nusdhub!rwhite From: rwhite@nusdhub.UUCP (Robert C. White Jr.) Newsgroups: comp.unix.wizards Subject: Re: Unix File Locks Message-ID: <1311@nusdhub.UUCP> Date: 7 Apr 89 02:02:37 GMT References: <538@bdt.UUCP> Distribution: na Organization: National University, San Diego Lines: 43 in article <538@bdt.UUCP>, david@bdt.UUCP (David Beckemeyer) says: > My question is: Isn't there a race condition between the stat and creat? Shure there is, but the lockfile mechanisim is defined so that "he who creates the lockfile first gets the device. The stat is mostly useful only if the code does a cleanup/verify attempt. Since your example is simply check1-or-exit, check2&lock-or-exit there multipath along which the race condition produces an undefined result. The "most correct" example I can think of for intellegent locking is the HBD uucp method which goes somewhat like this: (psudocode) { if stat succedes { attempt validate-and-remove by reading the contents of the lock file and trying to kill(0) the process number therein. If the process is running {return failure} else {remove lockfile}} (AT this time, if more than one program is contending, the remove may meet with an error but we don't care, the first person to create a valid lockfile wins. If you get to here, it is a free-for-all; if you didn't get to here you already failed so the race condition is moot) if create fails { return failure } continue processing } Since all resource locking is a race condition by nature this structure makes the important part of the race occur only within the create call, which is about the tightest granularity you can hope for. A slightly tighter method is to place a lock on the region of the old file before gettign to the meat of the kill(0), then if there is no such process you can simply palce your process number in the existing file. The lock and alter method removes the window of vunerability between the subsiquent commands, and thereby tightening the algorithm. the down side of this is that EVERY program which contends on the resource MUST (either or both of) use the lock method (with manners) and/or set the manditory locking flag durring creation, something many programmers might not think of checking or doing without very spesific instructions. Share and Enjoy, Rob.