How Linux Implements File Locking Mechanisms

File locking in Linux is a synchronization mechanism designed to prevent race conditions and data corruption when multiple processes access the same file concurrently. The Linux operating system implements this functionality at the kernel level using both advisory and mandatory locking paradigms, exposed to userspace through key system calls including flock(), fcntl(), and lockf(). These mechanisms allow applications to negotiate shared or exclusive access to entire files or specific byte ranges, coordinating input/output operations while maintaining system stability and performance.

Advisory vs. Mandatory Locking

Linux supports two distinct locking philosophies:

Core System Calls for File Locking

Linux provides several programmatic interfaces to manage file locks:

1. flock()

Originating from BSD, flock() applies locks to whole files only. It accepts two primary lock modes:

flock() locks are associated with the underlying open file table entry (the struct file in the kernel), rather than the process or the inode alone. This means that if a file descriptor is duplicated via fork() or dup(), the child or duplicate shares the same lock reference.

2. fcntl() (POSIX Locks)

POSIX record locking via the fcntl() system call provides fine-grained control, allowing processes to lock arbitrary byte ranges within a file rather than the entire file.

Traditional POSIX locks possess unique ownership semantics:

To resolve the limitation where closing one descriptor drops all locks across the process (which poses issues in multi-threaded programs), modern Linux kernels introduce Open File Description (OFD) locks via fcntl(). OFD locks combine byte-range precision with flock() inheritance semantics, binding the lock to the open file description rather than the PID.

3. lockf()

The lockf() function is a standard C library interface that acts as a simplified wrapper around fcntl(). It operates strictly on byte ranges starting from the current file offset.

Kernel Implementation Details

Under the hood, the Linux Virtual File System (VFS) handles file locking using internal data structures: