Full name: File control (fcntl) and advisory locking.
Definition
Advisory locking is a way for cooperating processes to take turns with a file: a process asks the kernel for a lock on the file, and the kernel refuses or delays a conflicting lock request from another process, but stops no process from reading or writing the file without asking. A lock is shared (several holders, usually readers) or exclusive (one holder). fcntl, short for file control, is the Unix system call that, among other jobs, sets such locks. Python’s §12.23 fcntl module exposes it and a second locking call, flock.
The idea
Two copies of a backup script start in the same minute and both write the same archive. A mutex §9.5 inside one program cannot help, because the copies are separate processes with separate memory. A lock kept by the kernel can: each copy asks for an exclusive lock on an agreed file, and the second copy waits or gives up. The lock is advisory because the kernel enforces it only against other lock requests; a program that never asks can still write the file. It is a sign on a door, not a bolt.
Whether the scheme works depends on two facts: the kernel object to which the lock is attached, and the event that releases the lock. Linux offers three kinds of lock that differ in both, and a Python file object does not show which kind a program uses.
How it works
Three kernel objects stand between a path and a lock.
The inode (index node) is the file system’s record of one file: its size, its owner and the location of its data. A directory entry maps a name to an inode. Several names can map to one inode, and a name can later be made to map to a different inode.
The open file description is the record that one
opencall creates in the kernel. It holds the current file offset and the access mode and points to the inode.The file descriptor §15.21 is a small integer in one process’s table that points to an open file description.
dupcopies a descriptor within a process, andfork, which creates a child process, copies all of them into the child; the copies point to the same open file description. A secondopenof the same path creates a new open file description.
The kernel keeps each lock with the inode, together with an owner. Two lock requests conflict when they concern the same inode, come from different owners, cover overlapping bytes, and at least one of them is exclusive.
flock locks, set with fcntl.flock(f, fcntl.LOCK_EX) in Python. The owner is the open file description, and a lock always covers the whole file. Descriptor copies made by dup or fork share the lock. It is released by the operation LOCK_UN through any of those copies, or when the last descriptor that points to the open file description is closed, which also happens when the last process holding such a descriptor ends. Changing a held shared lock into an exclusive one is not guaranteed to be atomic: the existing lock is removed first, so another process can take the lock in between.
Traditional POSIX (Portable Operating System Interface) record locks, set with the fcntl commands F_SETLK and F_SETLKW, the second of which waits; Python’s fcntl.lockf uses these commands. The owner is the process, and a lock covers a range of bytes; a length of 0 means up to the end of the file, however far it grows. A child created by fork does not inherit the locks. Threads of one process share them, so these locks do not keep threads of one process apart. A lock is released by unlocking its range, when the process ends, or when the process closes any descriptor for the same inode, even one that unrelated code in the process opened separately. An exclusive lock needs a descriptor opened for writing.
Open file description locks, available on Linux 3.15 and later through the commands F_OFD_SETLK and F_OFD_SETLKW of fcntl.fcntl. They cover byte ranges like record locks but are owned by the open file description like flock locks. So they are shared with descriptor copies, survive the closing of unrelated descriptors, and are released by unlocking or by the last close of their open file description. Threads that each open the file get separate open file descriptions and therefore exclude each other.
How the kinds interact. On a local Linux file system, flock locks and record locks do not see each other, while open file description locks and traditional record locks do conflict, even within one process. Over NFS (Network File System), Linux since version 2.6.12 implements flock locks as whole-file record locks, so there all kinds interact, and an exclusive flock lock then needs the file opened for writing. Mandatory locking, in which the kernel also blocks ordinary reads and writes, is not part of POSIX, and Linux no longer supports it from version 5.15.
The Python side. Each lock function takes a descriptor number or any object with a fileno() method, such as a file object returned by open. Closing the file object closes its descriptor. Adding LOCK_NB to a request makes the call fail at once with an OSError instead of waiting.
Worked example
flock and descriptor copies. Process A runs f = open("/run/job.lock", "w"), receives descriptor 3, and calls fcntl.flock(f, fcntl.LOCK_EX). The open file description now has 1 descriptor pointing to it. A calls os.dup(3) and receives descriptor 4: 2 descriptors, 1 lock. A closes descriptor 3: descriptor remains, and the lock stays. Process B opens the same file, which creates a second open file description, and asks for LOCK_EX | LOCK_NB. The request fails, because a different owner holds an exclusive lock on the same inode. A closes descriptor 4: descriptors remain, the open file description disappears and the lock is released. B’s next request succeeds.
The record-lock trap. Process A opens /data/state.db for reading and writing as descriptor 5 and calls fcntl.lockf(f, fcntl.LOCK_EX), an exclusive record lock on the whole file. Later a function in another part of A reads the file’s header with Path("/data/state.db").read_bytes() from pathlib §12.39, which opens the file as descriptor 6, reads, and closes descriptor 6. That close releases every record lock that A holds on the inode, although descriptor 5 is still open. B’s next lockf call succeeds, and A and B now both write. Had A used an flock lock or an open file description lock, closing descriptor 6 would have released nothing, because descriptor 6 had an open file description of its own, which held no lock.
Replacing the lock file. A holds an flock lock through /run/job.lock, which maps to inode 1001 (a made-up number). A clean-up script deletes /run/job.lock. B opens /run/job.lock with mode "w", which creates a new file with inode 1002, and locks it at once. The two locks are on different inodes, so they do not conflict, and A and B both believe that they hold the only exclusive lock. Renaming a new file over the lock file has the same effect. Two rules prevent it. Never delete or replace a lock file that may be in use. Or, after taking the lock, compare the device and inode numbers of the open file (os.fstat(f.fileno())) with those of the path (os.stat(path)), and start again if they differ. The comparison is sound because an inode that is still open cannot be freed, so its number cannot be given to a new file while A holds it.
Stated precisely
Model a lock as a record : the inode , the owner , the type (shared or exclusive) and the byte range , which for flock is the whole file. Two locks and of kinds that see each other conflict exactly when , , and overlap, and or is exclusive. A request that conflicts with a held lock waits, or fails at once with LOCK_NB or F_SETLK.
Owner and release, per kind:
flock: owner is the open file description; released by
LOCK_UNthrough any descriptor that points to it, or when the last such descriptor, in any process, is closed.Traditional record lock: owner is the process; released by unlocking the range, by the process closing any descriptor that refers to the inode, or by the process ending; not inherited by
fork.Open file description lock: owner is the open file description; released by unlocking the range or when the last descriptor that points to it is closed.
The scheme protects the data only under three assumptions. (1) Every program that touches the file takes a lock of a compatible kind before touching it. (2) All of them lock the same inode, which requires that the lock file’s name is not made to map to another inode while the lock may be held. (3) The file system implements the locks as described above; network file systems, such as NFS, implement them through a locking protocol of their own.
Limits and common mistakes
An advisory lock binds only programs that ask for it. A program that opens and writes the file without locking is not stopped.
A lock says nothing about the state of the data. If the holder crashes in the middle of a write, the kernel releases the lock when the process ends, and the next holder finds a half-written file. A lock is not a transaction §8.7; recovery from a partial write needs its own mechanism.
Release a lock explicitly: unlock it, or close the file, for example by leaving a with open(...) as f: block. Do not rely on the moment at which Python frees the file object. CPython, the standard implementation of Python, written in C, frees an object when its reference count reaches zero (reference counting §9.22) and closes the file then, but objects caught in reference cycles wait for the cycle collector, and other implementations, such as PyPy, free objects later.
A child process can keep an flock lock alive. After os.fork, the child holds copies of the parent’s descriptors, so the lock stays held until the child also closes its copy or ends. Python’s subprocess module passes no extra descriptors to its children by default, but os.fork copies all of them.
A process can wait for itself. If one process opens the lock file twice and takes an exclusive flock lock through each open file description, the second request conflicts with the first and, without LOCK_NB, waits forever: a deadlock §9.14. With traditional record locks the reverse surprise occurs: a process never conflicts with itself, so the locks give no protection between its threads.
Questions answered
Which file object or inode carries the lock, and what releases it?
The kernel keeps the lock with the inode, the file system’s record of the file, that the descriptor reached when the file was opened; it does not keep it with the path name or with the Python file object. The owner recorded with the lock, and therefore the release rule, depends on the kind of lock.
fcntl.flock: the owner is the open file description, the kernel record that oneopencall creates and that descriptor copies made byduporforkshare. The lock is released by an explicitLOCK_UNthrough any of those copies, or when the last of them is closed.fcntl.lockfand thefcntlcommandsF_SETLKandF_SETLKW(traditional POSIX record locks): the owner is the process. The lock is released by unlocking, when the process ends, or when the process closes any descriptor for the same inode, even an unrelated one. A child created byforkdoes not inherit it.Linux open file description locks (
F_OFD_SETLK): the owner is the open file description, as with flock, but the lock covers a byte range.
A Python file object carries only a descriptor. Closing it, or leaving its with block, closes the descriptor, which releases an flock lock if no copy of the descriptor remains. Do not rely on the moment at which Python frees the object. Because the lock belongs to an inode, a process that opens the same path after the file was deleted or replaced locks a different inode and does not conflict with the old holder.
Related entries: File descriptor versus pathname (§15.21), Inode reuse (§15.24), Transaction (§8.7), Mutex (§9.5), Lease and exclusive ownership (§13.26), Reference counting (§9.22), Deadlock (§9.14). Further reading: [37, 131, 132].