$linuxjunkies
>

flock(1)

Manage file locks from the shell, allowing exclusive or shared access to files or file descriptors.

UbuntuDebianFedoraArch

Synopsis

flock [OPTION]... FILE COMMAND [ARG]...
flock [OPTION]... FD

Description

flock acquires a lock on a file or file descriptor, holding it for the duration of a command or script. Locks can be exclusive (write) or shared (read), and the command will wait until the lock is available unless you use nonblocking mode. This is useful for coordinating access to resources across multiple processes, particularly in shell scripts and cron jobs.

When used with a FILE argument, flock opens or creates the file and acquires the lock on it. When used with a file descriptor (FD), it operates on an already-open descriptor. The lock is automatically released when the command exits or the file descriptor is closed.

Common options

FlagWhat it does
-s, --sharedAcquire a shared lock (read lock) instead of exclusive; multiple processes can hold shared locks simultaneously
-x, --exclusiveAcquire an exclusive lock (write lock); default behavior, prevents other locks on the file
-n, --nonblockFail immediately if lock cannot be acquired instead of waiting; exit with code 1
-w, --wait SECONDSWait up to SECONDS for the lock; exit with code 1 if timeout expires
-u, --unlockRemove an existing lock; useful when lock file is passed as FD argument
-c, --closeClose the file descriptor before executing the command; lock is retained
-e, --exclusiveExplicitly set exclusive lock mode (same as -x)

Examples

Acquire exclusive lock on /tmp/mylock.lock, run backup.sh, then release; prevents concurrent backups

flock /tmp/mylock.lock -c 'backup.sh'

Try to acquire lock without waiting; if busy, skip sendmail queue processing to avoid conflicts

flock -n /var/lock/mail.lock sendmail -q

Use shared lock for read-only operation; multiple reads can happen concurrently

flock -s /tmp/data.lock grep 'pattern' /tmp/data.txt

Wait maximum 30 seconds for lock; exit with status 1 if timeout occurs

flock -w 30 /tmp/resource.lock command-with-timeout

Open file descriptor 3, lock it exclusively, then run critical section; lock persists for the shell session

exec 3> /tmp/script.lock && flock -x 3 && critical_section.sh

Unlock and release the lock held on file descriptor 4

flock -u 4

Redirect to file descriptor 200, acquire exclusive lock, execute database write, then unlock

{ flock -x 200; database-write; } 200>/tmp/db.lock

Related commands