flock — One Copy at a Time, and the Lock That Outlives the Script That Took It

ByLinuxtastic

November 29, 2026

A backup that takes forty minutes is scheduled every thirty. A queue worker is started by cron every minute “in case it died”, and on a slow day there are nine of them. A deploy script is run by two people at once. Every one of these is the same problem — a job that must not overlap with itself — and the Unix answer is to take a lock on a file for as long as the job runs. flock is the command that does it: it takes the lock, runs your command, and releases the lock when the command exits, however it exits, because the lock belongs to an open file descriptor and the kernel closes those when a process dies. That last property is why a lock file beats a PID file, which outlives a crash and has to be cleaned up by hand.

flock -n /run/lock/backup.lock /usr/local/bin/backup.sh

Open (creating if needed) the lock file, try to take an exclusive lock on it, and run the command if that succeeded. -n means do not wait: if another process holds the lock, exit immediately with status 1 and run nothing. Without -n, flock waits for the lock, which is what you want when the jobs must all run but one at a time. The file’s contents are irrelevant and it is normally empty; the lock is a property of the open file, not of anything written in it. Measured with two instances, the second arriving while the first held the lock:

$ flock -n lock1 sleep 3 &
$ flock -n lock1 echo "got it"; echo "rc=$?"
rc=1
$ flock -n -E 75 lock1 echo "got it"; echo "rc=$?"
rc=75
$ time flock -w 1 lock1 echo got; echo "rc=$?"
rc=1
real    0m1.002s
$ lslocks | grep lock1
flock             555 FLOCK      WRITE 0     0   0 /home/claude/work/cmd/lab2/lock1

The conflicting instance printed nothing and exited 1; -E 75 chose a different status for that case, so a caller can tell “lock busy” from the command’s own failure; -w 1 waited one second and then gave up. lslocks shows who holds what. When the command does run, flock exits with the command’s own status, so a cron line using it still reports the job’s failures.

The lock that outlives the script

The lock is released when the last descriptor referring to the open file is closed — and every child the script starts inherits that descriptor. A script that takes a lock, starts a helper in the background and exits has not released anything: the helper holds the lock until it exits, and the next run reports “already running” against a script that is not. Measured, with the descriptor form of the lock:

$ cat job2.sh
#!/bin/sh
exec 9>/tmp/job2.lock
flock -n 9 || { echo "already running"; exit 1; }
sleep 30 &            # a helper left running: inherits fd 9
exit 0
$ ./job2.sh; echo "job2 exited rc=$?"; ./job2.sh
job2 exited rc=0
already running
$ lslocks | grep -v environment
COMMAND           PID  TYPE SIZE MODE  M START END PATH
(unknown)         612 FLOCK      WRITE 0     0   0 /...
$ fuser -v /tmp/job2.lock
                     USER        PID ACCESS COMMAND
/tmp/job2.lock:      root        649 F.... sleep

Note what lslocks showed: the PID of the shell that took the lock, which no longer exists, as (unknown) with no usable path. /proc/locks records the locker, not the current holder, so once the locker is gone the way to find who really holds a lock is fuser -v on the lock file, which finds every process with it open. The fix is to keep the descriptor out of the children: in the descriptor form, sleep 30 9>&- & closes fd 9 for that command alone; in the command form, flock -o closes the lock descriptor before running the command, and flock itself keeps the lock until the command exits. Both were measured: with the fix, the second run went ahead.

Options

FlagMeaning
-n / --nonblockFail at once (status 1) if the lock is held, rather than waiting
-w SECSWait at most this long, fractions allowed, then fail as -n would
-E STATUSExit status to use when the lock could not be taken (default 1); lets the caller tell busy from broken
-x / -sExclusive lock (the default) / shared lock: any number of -s holders at once, none while an -x is held, and vice versa
-uRelease a lock on a descriptor without closing it (descriptor form only)
-oClose the lock descriptor before running the command, so children do not inherit it
-c 'COMMAND'Run the string through sh -c instead of exec’ing a program
-FExec the command in place of flock rather than forking; the command’s PID is then the one flock had (no -o possible)
--verboseReport how long the lock took and what was run
flock [opts] FILE CMD…Command form: lock a path (file or directory, created if a file and missing), run the command
flock [opts] FDDescriptor form: lock a descriptor the shell already opened (exec 9>file); the lock lasts until the descriptor closes

The two cron patterns

# in the crontab: nothing to change in the script
*/30 * * * *  flock -n /run/lock/backup.lock /usr/local/bin/backup.sh

# in the script: the lock is taken by the script itself
#!/bin/sh
exec 9>/run/lock/backup.lock
flock -n 9 || { echo "backup already running" >&2; exit 1; }
# ... the rest of the script; the lock is released when it exits

The crontab form is the one to reach for first: it needs no change to the script and no cooperation from it, and flock waits for the whole command, children and all, before releasing (which is also why the inherited-descriptor problem does not arise unless the script itself backgrounds something and exits — then use -o). The in-script form is for scripts that may be run by hand as well as by cron, and for scripts that need the lock for only part of their work. Decide what should happen on overlap before choosing the flag. -n skips the run, which is right for a backup (the next one is in thirty minutes) and wrong for a queue drain that must eventually happen; for the latter, -w with a bound, or no flag and let the runs queue, and watch for the backlog. /run/lock is world-writable with the sticky bit set, on tmpfs, cleared at boot; it is the right place for a lock that should not survive a reboot. A lock file in a directory that only root can write to is a lock only root can take, which is sometimes the point and sometimes the bug. cron and The Life of a Scheduled Job cover the rest of what goes wrong on a schedule; a systemd service started by a timer cannot overlap itself at all, because a unit that is already active is not started again, which is one of the arguments for systemd Timers.

Shared locks, and locking the script itself

$ flock -s /tmp/sh.lock sleep 2 &
$ flock -s -n /tmp/sh.lock echo "second reader ok"
second reader ok
$ flock -x -n /tmp/sh.lock echo "writer ok"; echo "writer rc=$?"
writer rc=1

Shared locks are for the many-readers-one-writer shape: several report jobs may read a data directory at once, but the job that rewrites it must wait until none of them is running, and they must wait while it does. Readers take -s, the writer takes -x, and the kernel does the rest. A less obvious trick is to lock the script file itself — exec 9<"$0" then flock -n 9 — which needs no separate lock file and works even though the script is opened read-only, because an exclusive lock does not require write access. Measured: a second instance of such a script was refused while the first ran. The one thing it does not survive is editing the script with a tool that writes a new file and renames it into place, which gives the next run a different inode and therefore a different lock.

Never delete the lock file

$ flock /tmp/del.lock sleep 5 &
$ rm /tmp/del.lock
$ flock -n /tmp/del.lock echo "second instance got the (new) lock"
second instance got the (new) lock

The lock is on the inode, and rm removes the name. The first job still holds its lock on a file that no longer has a name; the second job creates a new file at the same path and locks that, and now two copies are running. This is the single most common way a working lock stops working: a tidy-up script, a tmpwatch or systemd-tmpfiles rule on /tmp, or an operator who “cleaned up the stale lock file” because a PID-file habit said that was the fix. There is no stale lock file with flock; an unheld lock file is harmless and an empty one tells you nothing. Put the lock under /run/lock, not /tmp, and if something must be deleted, delete it only while holding the lock.

Where it does not reach

flock is advisory: it stops other flock callers, not a process that opens the file and writes without asking. It is per machine; two hosts sharing a directory over NFS get the kernel’s emulation of flock as a POSIX byte-range lock, which works between NFS clients on modern kernels, does not reliably interact with processes on the server itself, and is not available on some other network filesystems — for cross-host exclusion use the application’s own mechanism, or a database row, and treat a file lock as local. And it is one lock per open file description: the same process taking the same lock twice through a second open() blocks against itself, which surprises people who wrap a locked script in another locked script using the same path. The Life of a File Descriptor has the table of the three locking mechanisms and what each attaches to; the short version is that flock attaches to the open file description, which is exactly what makes inheritance and fuser behave as this page describes.

Common problems

SymptomCauseCheck / fix
“Already running” but no job is runningA background child inherited the lock descriptorfuser -v lockfile; close the fd in the child (9>&-) or use flock -o
lslocks shows (unknown) and /...The process that took the lock has exited; a child holds itfuser -v on the file, or /proc/*/fd
Two copies running despite the lockLock file was deleted and recreated; or different paths to the lock; or NFSNever rm the lock; lock under /run/lock; one canonical path
Job silently never runs-n and something holds the lock permanently (a hung earlier run)fuser -v; add -E and log the busy case; consider timeout on the job
Permission denied on the lock fileDirectory not writable by the job’s user, or file owned by another userA lock file per user, or a group-writable directory; the file itself may be read-only
Cron mail every run saying the lock is busyJob takes longer than its intervalFix the interval or the job; -n … || exit 0 if skipping is fine and you do not want the mail
Locked script edited, two instances appearLocking $0 and the editor replaced the file (new inode)Use a dedicated lock file
Script deadlocks on itselfSame lock path taken twice through separate opens in one process treeTake it once, at the top, and pass the descriptor down

Quick reference

flock -n /run/lock/job.lock cmd            # skip if another copy is running
flock -w 60 /run/lock/job.lock cmd         # wait up to a minute, then skip
flock -n -E 75 lock cmd                    # busy exits 75, cmd's own status otherwise
flock -o -n lock cmd                       # cmd's children do not hold the lock
flock -s lock reader; flock -x lock writer # many readers or one writer
exec 9>/run/lock/job.lock                  # in-script form...
flock -n 9 || exit 1                       # ...take it (release = script exit)
helper 9>&- &                              # ...start a child without the lock
flock -u 9                                 # ...release early, keep fd open
exec 9<"$0"; flock -n 9 || exit 1          # lock the script file itself
lslocks                                    # who holds which locks (locker PID)
fuser -v /run/lock/job.lock                # who actually has the lock file open
grep lock /proc/locks                      # the kernel's own list

Related reading

  • cron — the scheduler whose overlapping runs flock exists to prevent
  • The Life of a Scheduled Job — the eight stages of a job, including the one where two copies meet
  • systemd Timers — a service unit cannot overlap itself, which removes the need for a lock
  • The Life of a File Descriptor — the open file description a flock lock belongs to, inheritance, and the three locking mechanisms side by side
  • lsof and fuser — finding which process has the lock file open when lslocks cannot say
  • Automated Backups — a job that must never run twice at once, set up end to end