Flock
This article is about the command flock that is used to implement advisory locking in shell scripts. The locks are advisory in the sense that they only affect other processes that also lock the same file or directory. Other processes are free to ignore the lock entirely, even if they use, delete or change the file or directory which is being locked. The capabilities use the same-named flock(2) system call, and thus do coordinate with other processes that use the system call instead of the command.
There are two main forms of the command, one naming the file or directory, and the other naming an open file descriptor.
Using a name
flock [-sxon] [-w timeout] resource [-c] command...
- This form wraps a lock around the executing command. Given appropriate permissions, a file with that name will be created if it does not already exist. It is okay if it is an already-existing directory.
Using a file descriptor
flock [-sxon] [-w timeout] fd
- This form is generally used for multiple commands, and often with an idiom that creates the file descriptor just long enough for the commands to execute:
{
flock -n 9 || exit 1
# commands protected by the lock
} 9<SomeResource
Note: file descriptors larger than 9 are not fully portable. Output redirection could be used, but could of course change something.
Options
-s, --shared
- Form a shared lock (a.k.a. a read lock)
-x, -e, --exclusive
- Form an exclusive lock (a.k.a. a write lock) (this is the default)
-n, --nb, --nonblock
- if the lock cannot be obtained immediately, fail with an exit code of 1. Do not wait for the lock.
-w, --wait, --timeout seconds
- allow seconds seconds for obtaining the lock. If it still cannot be obtained, fail with exit code of 1. Decimal fraction seconds are understood.
-o, --close
- Unlocks the resource before executing the command. Uncommon, but useful if the command spawns a child process which should not hold the lock.
-u, --unlock
- Unlocks the resource. Uncommon, but useful if the protected commands have forked a background process which should drop the lock.
-c, --command command
- Execute the single command under the lock.
-h, --help
- Display a help message.
Tricky Things
Facts that may not be obvious, and may not be portable, but are true in Ubuntu 14 and 16:
- Locking survives renaming, and moving within a single filesystem.
- a script may lock itself to prevent multiple executions
- even while locked, a script may rename itself, for instance to indicate that it is running, or has been run.
Provided by
Most (all?) Linux distributions incorporate this from the [util-linux] project.