I am using POSIX mandatory file locks through fcntl
. I'm wondering if those locks are reentrant, ie. can a process acquire a lock it already owns ?

- 40,153
- 18
- 88
- 147
-
Are you sure you mean *mandatory* file locks? Last time I looked, POSIX did not support mandatory locks. – cdarke Nov 04 '12 at 15:50
-
@cdarke Oups ! I meant advisory... Thanks for reporting. – paradigmatic Nov 04 '12 at 15:58
-
No `fcntl` locks are not re-entrant. You have to manually wrap the locking and unlocking codes with valid checks. And the `fcntl` behavior may vary based on your implementation system. – askmish Nov 04 '12 at 16:05
-
Fair enough. The wording of the POSIX standard on this is ambiguous, it says "An exclusive lock shall prevent any other **process** from setting a shared lock or an exclusive lock on any portion of the protected area." However for F_SETLKW is says: "the **thread** shall wait until the request can be satisfied". Suck it and see in your implementation? – cdarke Nov 04 '12 at 16:05
1 Answers
Advisory locks through fcntl
are on a per process base and just accumulate locked intervals on the file for the given process. That is, it is up to the application to keep track of the intervals and any unlock call for an interval will unlock it, regardless on how many lock calls had been made for that interval.
Even worse, the closing of any file descriptor for the file cancels all locks on the file:
As well as being removed by an explicit F_UNLCK, record locks are automatically released when the process terminates or if it closes any file descriptor referring to a file on which locks are held. This is bad: it means that a process can lose the locks on a file like /etc/passwd or /etc/mtab when for some reason a library function decides to open, read and close it.

- 76,821
- 6
- 102
- 177
-
You don't have to track ownership yourself. Since `fcntl` locks record owners and there's an API to read the current owner, you can simply see if you're the owner before locking, and if so, skip the lock/unlock steps. – R.. GitHub STOP HELPING ICE Nov 04 '12 at 17:39
-
@R.. you mean the `l_pid` field of the structure? This is not suitable to keep track of multiple locks by the same process, it only tells you (one of) the process that would block you, not if you already hold (part of) the range for the same process. – Jens Gustedt Nov 04 '12 at 17:50
-
If you're making complex use of overlapping ranges, then yes, I agree. I'm assuming either whole-file locks or locks of non-overlapping ranges where you can assume that, if anything in the range is locked, the whole range is locked by a single process. – R.. GitHub STOP HELPING ICE Nov 04 '12 at 18:03