Search code examples
file-lockingflock

What happens if another process tries to write to a flock(2)'d file?


Specifically, if the following events take place in the given order:

  1. Process 1 opens a file in append mode.
  2. Process 2 opens the same file in append mode.
  3. Process 2 gets an exclusive lock using flock(2) on the file descriptor.
  4. Process 1 attempts to write to the file.

What happens?

Will the write return immediately with a code indicating failure? Will it hang until the lock is released, then write and return success? Does the behavior vary by kernel? It seems odd that the documentation doesn't cover this case.

(I could write a couple processes to test it on my system, but I don't know whether my test would be representative of the general case, and if anyone does know, I can anticipate this answer saving a lot of other people a lot of time.)


Solution

  • The write proceeds as normal. flock provides advisory locking. Locking a file exclusively only prevents others from getting a shared or exclusive lock on the same file. Calls other than flock are not affected.