Skip to content

fcntl File Lock ​

fcntl 提供跨 process 的 read/write file lock,但 lock 屬於 process,不屬於 thread 或 fd。

坑:同一 process 不能跨 thread 共用 ​

If a process closes any file descriptor referring to a file, then all of the process's locks on that file are released, regardless of the file descriptor(s) on which the locks were obtained.

  • Thread 1、Thread 2 都對 mydata.lock 上 read lock
  • 其中一個 unlock 或 close fd → 整個 process 失去這把 lock
  • 另一個 thread 以為自己還持有,實際上已經沒有保護

解法 ​

  • 每個 thread 用不同的 lock 檔(拆成多把 lock)
  • 或在 process 內另外用 mutex / 計數管理,只由一個地方持有 fcntl lock
  • Linux 3.15+ 可考慮 OFD lock(F_OFD_SETLK),lock 綁在 open file description 上

參考 ​

頁面歷史

Just observe 👀