File Lock

Is File lock supported in cluster filesystems?

Yes, newer version of NFS and OCFS2 both support flock.

fcntl, flock or lockf?

All of these three functions can lock a file. Which one to use? Here are some tips:

  • Use one of them through you codes.
  • Use the same one other codes of your existing program uses.
  • Use fcntl if a locking utility is first chosen:
    • fcntl is NFS safe, while flock and lockf are not.
    • when the program dies for whatever reason (even kill -9, which is not trappable to explicitly remove the lock), the lock disappears.

Using flock to manage locks from shell scripts

flock is usually used the following manner:

(
    flock -s 200
    # ... commands executed under lock ...
) 200>/var/lock/mylockfile

Python Locks

  • threading.Lock() - for inter-thread communication.
  • multiprocessing.Lock() - for inter-process communication. Only useful when all the processes are in the same host, because it leverage semaphores provided by the operating system.

FileLock (last edited 2010-03-11 00:29:22 by ZhigangWang)