Linux File Locking: flock, lockd, and NFS Locking Explained (2026 Guide)
Objective
This guide explains how file locking works on Linux, covering local locking with flock, the NFS lock daemon lockd, and how locking behavior changes between NFSv3 and NFSv4. By the end, you will understand:
- What file locking is and why it matters for both local and network filesystems
- The difference between advisory and mandatory locking on Linux
- How to use
flockfrom the command line and in scripts - How
lockdfits into the NFSv3 stack and what changed in NFSv4 - How to diagnose and recover from stale NFS locks in production
- Where file locking connects to RHCSA exam objectives around NFS
Two processes write to the same file at the same time without coordination. The result is corrupted data: interleaved writes, truncated content, or a file that's half one version and half another. File locking is the mechanism that prevents this. On a local filesystem it's straightforward. Across NFS it's historically been one of the more complex and fragile parts of Linux system administration.
Advisory vs Mandatory Locking: The Linux Model
Before anything else, understand how Linux approaches locking, because it's different from what many people expect.
- Advisory locking is the default and by far the most common type on Linux. A lock is a signal between cooperating processes. Any process that checks for a lock before writing will respect it. A process that ignores the lock mechanism entirely can still write to the file without obstruction.
- This sounds weak, and in some ways it is, but in practice it's sufficient because well-written applications always check for locks before writing
- Most file locking you'll deal with in real administration is advisory: cron jobs, package managers, databases, and service PID files all use advisory locks
- Mandatory locking is enforced by the kernel itself. Even a process that doesn't check for locks cannot write to a file that's locked. On Linux, mandatory locking exists but is considered unreliable, poorly supported, and actively discouraged.
- It requires a filesystem mounted with the
mandoption and a specific permission bit set on the file - In practice, virtually no production software relies on Linux mandatory locking. If you need enforced coordination, applications use advisory locks and are written to respect them.
- It requires a filesystem mounted with the
For everything in this guide: when we say "file locking," we mean advisory locking unless stated otherwise.
Two Lock Types: flock and fcntl/POSIX Locks
Linux has two distinct locking APIs, and they don't interact with each other. This trips up a lot of sysadmins who assume all locks work the same way.
- flock locks (BSD-style)
- Apply to an entire file, not a range within it
- Come in two varieties: shared (read) locks and exclusive (write) locks
- Multiple processes can hold a shared lock simultaneously
- Only one process can hold an exclusive lock, and only when no shared locks exist
- Released automatically when the file descriptor is closed or the process exits
- Available from the command line via the
flockutility
- POSIX locks (fcntl-style)
- Can lock specific byte ranges within a file, not just the whole file
- Used by databases and applications that need fine-grained concurrent access to different parts of the same file
- Behave differently with
fork(): child processes do not inherit POSIX locks - Not directly accessible from the command line, only via system calls in code
From a sysadmin perspective, flock is what you'll use and encounter most often. POSIX locks are an application-level concern that surfaces in troubleshooting when database or application locks behave unexpectedly.
Using flock from the Command Line
flock is a utility that wraps a command inside a file lock. It's one of the most practically useful tools in a sysadmin's script toolkit for preventing concurrent execution of the same job.
Basic Usage
# Run a command while holding an exclusive lock on a lock file
# If another process holds the lock, flock waits until it's free
flock /var/lock/myjob.lock /usr/local/bin/backup.sh
# Specify a timeout: wait up to 10 seconds, then give up
flock --timeout 10 /var/lock/myjob.lock /usr/local/bin/backup.sh
# Non-blocking: fail immediately if lock is already held
flock --nonblock /var/lock/myjob.lock /usr/local/bin/backup.sh
Using flock in Shell Scripts
The file descriptor form is more flexible and is the pattern used in most production scripts:
#!/bin/bash
# Prevent this script from running more than one instance at a time
LOCKFILE=/var/lock/mybackup.lock
# Open the lock file on file descriptor 9
exec 9>"$LOCKFILE"
# Try to acquire an exclusive lock, fail immediately if already locked
if ! flock --nonblock 9; then
echo "Another instance is already running. Exiting."
exit 1
fi
# Lock acquired. Do the work here.
echo "Running backup..."
/usr/local/bin/backup.sh
# Lock is released automatically when the script exits and fd 9 is closed
Checking for Existing Locks
# View all current file locks on the system
cat /proc/locks
# More readable output showing process names
lslocks
# Check locks on a specific file
lslocks | grep filename
# See which process holds a specific lock
lsof /var/lock/myjob.lock
Output from /proc/locks is dense. lslocks from the util-linux package is much more readable and shows the type, mode, PID, and path for every active lock on the system.
Real Production Use Cases for flock
- Preventing duplicate cron jobs:
- A backup script that takes 90 minutes gets scheduled every hour
- Without a lock, two instances run simultaneously, doubling the load and potentially corrupting the backup output
- Wrap the cron command in
flock --nonblockand the second instance exits cleanly if the first is still running
- Serializing access to shared resources:
- Multiple scripts write to the same log file or config file
- flock ensures they queue up rather than interleave writes
- Coordinating deployments:
- Multiple deployment agents on the same host need to run one at a time
- A shared lock file acts as the coordination point without a separate daemon
- Package management:
dnfandrpmuse their own lock files to prevent concurrent package operations- The error "Another app is currently holding the yum lock" is
flockdoing exactly its job
NFS Locking: How It Works
Local file locking is clean and well-understood. NFS locking adds a network layer and historically has been one of the least reliable parts of NFS. Understanding it helps you diagnose stale lock problems and configure NFS correctly.
NFSv3 and lockd
In NFSv3, file locking is handled by a separate protocol running outside NFS itself, the Network Lock Manager (NLM) protocol, implemented by the lockd kernel thread.
lockdruns on both the NFS server and the NFS client- It communicates over its own RPC service (
nlockmgr), separate from the NFS protocol on port 2049 - Because locking runs separately from the filesystem protocol, it creates two distinct failure modes:
- Server crash without graceful shutdown: the client holds locks the server no longer knows about. When the server restarts, locks are gone from its view but the client still thinks they exist.
- Network partition: client and server disagree about lock state for the duration of the outage
rpc.statd(the Network Status Monitor) works alongsidelockdto notify clients when the server restarts, so they can reclaim their locks. This works when the network recovers gracefully, but not always after hard failures.
Key ports involved in NFSv3 locking (important for firewall configuration):
# See all active RPC services including lockd
rpcinfo -p
# Typical relevant entries:
# 100021 nlockmgr (lockd) - dynamic port by default
# 100024 status (rpc.statd) - dynamic port by default
# To pin lockd to a specific port (add to /etc/nfs.conf or /etc/sysconfig/nfs)
# [lockd]
# port=32803
# Then open that port in firewalld
firewall-cmd --zone=public --permanent --add-port=32803/tcp
firewall-cmd --zone=public --permanent --add-port=32803/udp
firewall-cmd --reload
NFSv4 and Built-in Locking
NFSv4 fixes the fundamental architectural problem of NFSv3 locking by building lock management directly into the NFS protocol itself. This is one of the most significant improvements NFSv4 brought over earlier versions.
- No separate lockd needed: locking is part of the NFSv4 protocol, handled over the same TCP port 2049 as all other NFS traffic
- This simplifies firewall configuration dramatically: you only need port 2049 open for a working NFSv4 stack, no additional ports for locking
- Lease-based locking: NFSv4 uses time-limited leases instead of persistent locks. A client must periodically renew its lease. If the server doesn't hear from a client within the lease period, it assumes the client is gone and releases the locks automatically.
- This solves the stale lock problem that plagues NFSv3: locks clean themselves up when the client disappears
- No rpcbind dependency for locking: NFSv4 doesn't need rpcbind for its locking mechanism, further simplifying the service stack
On modern RHEL systems, NFSv4 is the default and recommended version. If you're configuring a new NFS setup, use NFSv4 unless you have a specific reason to use an older version.
Diagnosing and Clearing Stale NFS Locks
Even with NFSv4, stale locks happen. This is one of the more common NFS support issues in production environments, and knowing how to diagnose and clear them without a full server restart is a valuable skill.
Identifying Stale Locks
# On the client: see all current locks including NFS locks
lslocks
# Check for NFS-related lock messages in the system log
journalctl -u nfs-client.target --since "1 hour ago"
journalctl | grep -i "nfs\|lock\|stale"
# On the server: check NFS lock state
cat /proc/fs/nfsd/clients/*/states 2>/dev/null
# Check the NFS server's exported share status
exportfs -v
Clearing Stale NFSv3 Locks
# On the client: unmount and remount the NFS share
umount /mnt/nfsshare
mount /mnt/nfsshare
# If the mount is busy, find what's using it
lsof /mnt/nfsshare
fuser -m /mnt/nfsshare
# Force unmount if necessary (use with caution on production)
umount -f /mnt/nfsshare
# Restart the lock daemon on the client
systemctl restart nfs-client.target
# On the server: restart the NFS lock service
systemctl restart nfs-server
Clearing Stale NFSv4 Locks
# NFSv4 lease expiry is usually automatic, but to force state reset on the server:
# First, confirm what's connected
cat /proc/fs/nfsd/clients/*/info 2>/dev/null
# Restart the NFS server to clear all client state
# (Clients with active mounts will reconnect and reclaim within the lease period)
systemctl restart nfs-server
# On the client: if remounting doesn't clear the lock state
systemctl restart nfs-client.target
NFS Locking and Firewall Configuration
This is where NFS locking knowledge directly connects to RHCSA exam skills. Getting NFS working through firewalld requires opening the right services and ports, and the requirements differ between NFSv3 and NFSv4.
- NFSv4 only (recommended for new setups):
- Only port 2049 TCP needs to be open
- locking is built into the protocol, no extra ports needed
- NFSv3 with locking (legacy or mixed environments):
- Port 2049 for NFS itself
- Port 111 for rpcbind
- A pinned port for
lockd(configured in/etc/nfs.conf) - A pinned port for
rpc.statd - A pinned port for
rpc.mountd
# Simplest approach: use the nfs service definition in firewalld (covers NFSv4)
firewall-cmd --zone=public --permanent --add-service=nfs
firewall-cmd --reload
# Verify what the nfs service definition includes
firewall-cmd --info-service=nfs
# For NFSv3 compatibility, also add:
firewall-cmd --zone=public --permanent --add-service=rpc-bind
firewall-cmd --zone=public --permanent --add-service=mountd
firewall-cmd --reload
File Locking and the RHCSA Exam
File locking with flock and lockd are not listed as standalone objectives on the RHCSA 10 exam blueprint. Being honest about that matters, so you don't spend exam-prep time drilling commands that won't appear as explicit tasks.
Where this knowledge does connect to tested objectives:
- NFS configuration is a direct RHCSA objective. The exam tests mounting NFS shares, writing correct fstab entries for them, and configuring autofs for automatic mounting. Understanding how locking works in the NFS stack, especially the NFSv3 vs NFSv4 distinction, helps you configure NFS correctly and troubleshoot it when it doesn't work.
- NFSv4 mounts require fewer open firewall ports than NFSv3. Knowing why means you can diagnose a mount that works but locks don't, versus a mount that fails entirely.
- firewalld configuration is a direct RHCSA objective. Opening the right services for NFS (and knowing which services are needed for which NFS version) is exactly the kind of combined knowledge the exam tests.
- A task that says "configure this server to share a directory over NFS and allow client access through the firewall" requires knowing what to open
- Script writing and cron scheduling are tested. Using
flockto prevent duplicate cron job execution is a real pattern that appears in exam-style scenarios involving scheduled tasks and service management.
Where to focus exam prep time: NFS mounting and fstab are the core skills. File locking understanding supports that knowledge and rounds out your ability to troubleshoot NFS issues, but it's not the primary thing to drill.
Common Mistakes
- Assuming all processes respect advisory locks. A process that doesn't check for locks before writing will bypass them entirely. flock only works as coordination between processes that are written to use it.
- If you're seeing concurrent write corruption despite using flock, check whether every process in the chain is actually acquiring the lock before writing
- Using the same lock file path for different jobs. Two unrelated cron jobs using
/var/lock/job.lockwill block each other even though they have nothing to do with each other. Use unique, descriptive lock file names per job. - Opening NFSv3 locking ports without pinning them first.
lockduses a dynamic port by default. You can't write a firewall rule for a port you don't know. Always pin lockd and statd to fixed ports before adding firewall rules for them. - Trying to debug NFS lock issues on NFSv4 the same way as NFSv3. NFSv4 has no separate lockd process, no rpcbind dependency for locking, and uses lease-based rather than persistent locks. Troubleshooting commands and restart sequences differ between the two versions.
- Forcibly killing a process that holds a lock and expecting other processes to proceed immediately. With flock locks, the lock releases when the file descriptor closes. With POSIX locks, the behavior depends on the application. With NFS locks, the server may hold the lock state until the lease expires even after the client process is gone.
- Leaving lock files in /tmp. Lock files in /tmp get cleaned up on reboot, which is usually fine, but some system configurations clean /tmp periodically. A lock file that disappears while a process is running can allow concurrent execution where it shouldn't happen. Use
/var/lock/for persistent lock files.
Quick Reference
- Local locking with flock:
flock /var/lock/myjob.lock command: run command under exclusive lockflock --nonblock /var/lock/myjob.lock command: fail if lock unavailableflock --timeout 10 /var/lock/myjob.lock command: wait up to 10 secondslslocks: view all current lockscat /proc/locks: raw kernel lock table
- NFS locking diagnostics:
rpcinfo -p: list active RPC services including lockdlslocks | grep nfs: NFS-related locksjournalctl | grep -i lock: lock-related messages in the journal
- NFS lock recovery:
umount -f /mnt/nfsshare: force unmount (use carefully)systemctl restart nfs-client.target: restart client lock statesystemctl restart nfs-server: reset all client lock state on server
- Firewall for NFS:
firewall-cmd --permanent --add-service=nfs: NFSv4 (port 2049 only)firewall-cmd --permanent --add-service=rpc-bind: needed for NFSv3firewall-cmd --permanent --add-service=mountd: needed for NFSv3
How LinuxCert.Guru Helps You Practice This
NFS configuration is one of the consistently tested areas on the RHCSA exam, and it's a topic where the gap between reading about it and actually doing it is particularly wide. Understanding how locks, mounts, fstab entries, and firewall rules interact requires working through real scenarios on a real system, not just memorizing commands.
LinuxCert.Guru's filesystem and networking labs cover NFS mounting, fstab configuration, autofs, and firewall integration on real RHEL environments, with auto-graded tasks that verify the full configuration stack the same way the actual exam does.
Practice RHCSA NFS and filesystem labs at LinuxCert.Guru → https://linuxcert.guru
Conclusion
File locking on Linux is split between local locking (where flock is the command-line tool of choice) and network locking (where the mechanism depends heavily on which NFS version you're using). The two most important things to understand coming out of this guide:
- Advisory locking is the Linux default. Locks only work as coordination between processes that are written to check for them. They're not enforced by the kernel for uncooperating processes.
- NFSv4 built locking into the protocol. NFSv3 needed a separate
lockddaemon, extra firewall ports, and was fragile across server restarts. NFSv4 eliminated all of that by making locking part of the core protocol over port 2049. - For exam purposes: know NFS mounting, fstab, and firewall configuration. Understanding locking behavior helps you troubleshoot NFS problems and configure it correctly, but it's the mounting and persistence skills that are directly tested.
- For production: use flock in scripts wherever concurrent execution would cause problems. Cron jobs especially. The pattern is simple, the lock file is self-cleaning on process exit, and the cost of not using it when you should is data corruption that's hard to trace.
Start practicing RHCSA labs at LinuxCert.Guru → https://linuxcert.guru