6

Consider a situation where two processes make concurrent attempts at placing an exclusive lock on some file using flock(fd, LOCK_EX|LOCK_NB).

As indicated, the attempts are non-blocking, so one of the two processes is supposed to fail with EWOULDBLOCK.

Here is my question: Does the (Linux) implementation of flock() guarantee that exactly one of the two processes will succeed in every such case? Or, is it possible that both end up failing with EWOULDBLOCK even when nobody else are interfering?

In short, can flock(fd, LOCK_EX|LOCK_NB) ever fail spuriously with EWOULDBLOCK?

I am mainly interested in the version of flock() offered by Linux, but information about flock() on other systems, such as OS X, is most welcome.

Also, I assume that the answer is the same regardless of whether the locks are exclusive (LOCK_EX) or shared (LOCK_SH). If not, let me know.

Kristian Spangsege
  • 2,903
  • 1
  • 20
  • 43
  • If what you stated occurs it should be considered a bug. This is akin to 2 processes trying to acquire a mutex or semaphore and both failing when nothing is currently holding the lock. – Duck Jan 14 '14 at 15:49
  • Just out of curiosity: On which file system do you observer this? – alk Jan 15 '14 at 16:44
  • @alk I am not observing this. I am merely trying to access the correctness of the assumption that `flock(fd, LOCK_EX|LOCK_NB)` never fails spuriously. Do you know whether the flock() implementation depends on the file system? – Kristian Spangsege Jan 16 '14 at 03:13
  • 1
    `flock` doesn't work on some NFS file systems. It depends on the implementation. – Duck Jan 16 '14 at 16:32
  • @Duck But does EXT4 and BTRFS have different `flock()` implementation, for example? – Kristian Spangsege Jan 16 '14 at 17:19
  • @Kristian Spangsege, I don't know but I imagine you have already googled it. If there were problems I would guess it would have been widely reported. – Duck Jan 16 '14 at 18:33
  • @Duck These problems, even if they happen, are very rare. Locking typically takes less than 1/10 of a millisecond, and both processes need to call `flock` at the same time. It probably won't be so widely reported even if it is a problem. – elipoultorak Jan 02 '16 at 18:15

1 Answers1

1

Reading man flock(2):

EWOULDBLOCK The file is locked and the LOCK_NB flag was selected.

So getting EWOULDBLOCK means the file is already locked. If it is guaranteed that your two processes are the only ones involved, they will never get EWOULDBLOCK on the same file at the same time.

Please note that threads is a different story. Threads normally share file descriptors, so several threads within the same process can call flock() successfully on the same file.

alk
  • 69,737
  • 10
  • 105
  • 255
grebneke
  • 4,414
  • 17
  • 24