How to serialize command execution on linux?
flock
is really excellent for this. You can use flock
in a wrapper around your shell script, use it on the command line, or incorporate it into your script itself.
The best thing about flock
is that while it waits, it doesn't wait in a busy loop.
It also always cleans up the lock when your process exits / flock
exits.
Methods based on atomic file/directory creation can get locked out if the process exits without cleaning up (or if there is a kernel panic, or power failure, ...).
With flock
, the Linux kernel does the cleanup.
From the manual,
(
flock -s 200
# ... commands executed under lock ...
) 200>/var/lock/mylockfile
In this form you can wrap a specific block of code in your shell script.
Or you can run it like this,
/usr/bin/flock /tmp/lockfile command
If you don't want to block/wait indefinitely, you can specify a timeout:
-w --timeout <secs> wait for a limited amount of time
Or just use a non blocking argument:
-n --nonblock fail rather than wait