<story><title>Everything you never wanted to know about file locking</title><url>http://apenwarr.ca/log/?m=201012#13</url></story><parent_chain></parent_chain><comment><author>tedunangst</author><text>Every BSD system I&apos;m aware of has something called lockf, which may or may not be layered on top of flock (or the other way around).&lt;p&gt;Note that all of these locking schemes fall down hard on NFS, depending on client and server, regardless of what any man pages say about support.  Homework question: How does a stateless protocol like NFS remember when one client locks a file and a different client tries locking it?&lt;p&gt;The failure mode on NFS can vary from &quot;lock always succeeds, regardless of actual status&quot; to &quot;lock always fails, hanging forever&quot;, or my favorite, &quot;locks work, unless your process crashes, and then you can never lock that file again until you reboot the NFS server&quot;.</text></comment>
<story><title>Everything you never wanted to know about file locking</title><url>http://apenwarr.ca/log/?m=201012#13</url></story><parent_chain></parent_chain><comment><author>glhaynes</author><text>Good article. I don&apos;t quite understand this part, though:&lt;p&gt;&lt;i&gt;Still not convinced &lt;/i&gt;[that you shouldn&apos;t use mandatory locking]&lt;i&gt;? Man, you really must like punishment. Look, imagine someone is holding a mandatory lock on a file, so you try to read() from it and get blocked. Then he releases his lock, and your read() finishes, but some other guy reacquires the lock. You fiddle with your block, modify it, and try to write() it back, but you get held up for a bit, because the guy holding the lock isn&apos;t done yet. He does his own write() to that section of the file, and releases his lock, so your write() promptly resumes and overwrites what he just did.&lt;/i&gt;&lt;p&gt;If you&apos;re going to read some data and then potentially write modified data back over what you just read, shouldn&apos;t the first step before you even read it be to get a lock on the file or that range? Or, if your calculation might take a long time, at least get a lock right before you write it back, verifying first that you&apos;re writing over data that hasn&apos;t changed while you were off calculating?</text></comment>