|
|
|
|
|
by geofft
3678 days ago
|
|
> It is a common mistake to try to use files for locking, for example, instead of using the more robust flock(1). Why is this a mistake? It is my understanding that, if all the locking you need is a simple mutex, creating a file with a well-defined name with O_CREAT | O_EXCL is atomic -- the file will either be created or not (in which case the call will fail with EEXIST), and no two processes can possibly both succeed at creating the file. This even works on NFS; it was apparently broken in the NFS client in Linux 2.6.5 and below, but it is supposed to work in NFS, and is generally the only reliable way of getting locks in NFS. You don't get any better way to wait on the lock than re-trying to create the file, and you don't have any mechanism for dealing with clients that die while holding the lock (i.e., it's an aggressively CP system), but for what it does, it's supposed to work correctly and atomically. |
|
This gets rid of all the edge cases with stale locks in one fell swoop.
But as you point out if you want to do this e.g. over NFS you should create a file, but then you need to deal with stale locks.
If you can at all avoid that using flock() is generally better.