Skip to main content
Kill -9 Club
Sign in

flock

ShellPackage: util-linux

Takes a lock on a file for the duration of a command, so a second instance waits or gives up. It is what keeps a timer-launched backup from overlapping the previous one.

What its options do in the lessons

From the same glossary the lessons render under their commands, so the two cannot disagree.

flock -n
Gives up at once if the lock is already held, instead of waiting. Exits 1 and prints nothing: the option for a scheduled job, which will be started again anyway.
flock -w
Waits for the lock for at most that many seconds, fractions allowed, then fails the way -n does. -w 0 means the same as -n. Keep the timeout shorter than the scheduling interval, or waiting runs pile up.
flock -o
Closes the descriptor holding the lock before running the command, so a background process does not inherit it and keep the lock alive after the parent has finished.
flock -u
Drops the lock on an already-open descriptor (flock -u 9). Rarely needed — a lock goes when the descriptor closes — except when a background child might keep holding it.
flock --verbose
Says on standard error why the lock could not be taken (failed to get lock, timeout while waiting to get lock), or how long it took to get it. Without it a skipped run leaves no trace at all.

Lessons that teach it