Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!uxc!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.unix.wizards Subject: Re: Unix File Locks Message-ID: <16771@mimsy.UUCP> Date: 6 Apr 89 07:29:08 GMT References: <538@bdt.UUCP> Distribution: na Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 42 In article <538@bdt.UUCP> david@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@mimsy.umd.edu Path: uunet!mimsy!chris