flock and mktemp: Stopping Scripts Overlapping and Leaking Files

flock and mktemp: Stopping Scripts Overlapping and Leaking Files

Two problems that appear in every long-lived script, both with short fixes that most people reach for only after being bitten.

The overlap problem

*/5 * * * * /usr/local/bin/sync-data.sh

Runs every five minutes. Usually takes two. One day the remote end is slow and it takes seven.

Cron starts the next one anyway. Now two instances are writing the same files, and the failure mode depends on what the script does: duplicated work at best, corrupted output at worst, and a cascade where each run is slower because of the contention.

Why a PID file does not fix it

# the broken version, which everybody writes first
if [ -f /var/run/myjob.pid ]; then
    echo "already running"
    exit 1
fi
echo $$ > /var/run/myjob.pid
# ... work ...
rm -f /var/run/myjob.pid

Two problems:

It is not atomic. Two processes can both test, both find the file absent, and both create it. The window is small and it is not zero, and a job running every minute gets many chances.

It goes stale. Kill the process, or let the machine lose power mid-run, and the file remains. The next run sees a lock held by nothing and refuses to start, permanently, until somebody notices.

flock

#!/usr/bin/env bash
set -euo pipefail

exec 9>/var/lock/myjob.lock
flock -n 9 || { echo "already running, exiting" >&2; exit 0; }

# ... work ...

Three lines. What they do:

exec 9>/var/lock/myjob.lock opens file descriptor 9 on the lock file, creating it if needed.

flock -n 9 takes an exclusive lock on that descriptor, or fails immediately.

Nothing releases it explicitly, because the kernel does when the process exits. However it exits: normally, on error, on SIGKILL, on power loss.

That last property is what makes it correct where a PID file is not.

# wait instead of failing
flock -w 300 9 || { echo "timed out waiting for lock" >&2; exit 1; }

# wait indefinitely
flock 9

-n for scheduled jobs, where a second run is pointless and exiting 0 avoids a false alarm in your monitoring. -w for work that must happen but can be delayed.

Wrapping a command without editing it

# in the crontab, no script changes needed
*/5 * * * * flock -n /var/lock/sync.lock /usr/local/bin/sync-data.sh

# with a timeout
*/5 * * * * flock -w 60 /var/lock/sync.lock /usr/local/bin/sync-data.sh

This is the form to reach for when the script is not yours to modify. Our cron guide covers the crontab, and note that cron’s output handling means a lock failure with -n produces output and therefore an email, which is why exit 0 inside a script is often tidier.

systemd does this for you

# /etc/systemd/system/myjob.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/sync-data.sh

A systemd service cannot overlap with itself. Starting a unit that is already running does nothing. So for anything run from a timer, locking is already handled, which is one of the better arguments for timers over cron in our comparison.

Locking is still needed when the same work can be triggered from several places: a timer, a manual run, and a hook.

Where to put the lock file

# system-wide, cleaned at boot
/var/lock/myjob.lock
/run/lock/myjob.lock

# per user
"${XDG_RUNTIME_DIR:-/tmp}/myjob.lock"

/var/lock is a symlink to /run/lock on modern systems, so it is a tmpfs and clears at boot. That is correct for a lock. Our /var guide and XDG guide cover the locations.

Do not put it on NFS. flock over NFS has historically been unreliable, and a lock that silently does not lock is worse than none.

The temp file problem

# the broken version
tmp=/tmp/myjob.$$
command > "$tmp"
process "$tmp"
rm "$tmp"

Three things wrong.

$$ is predictable. PIDs are a small space and allocation is guessable, so an attacker can pre-create /tmp/myjob.12345.

/tmp is world-writable. Anybody can create files there. Which enables the attack: pre-create /tmp/myjob.12345 as a symlink to /etc/cron.d/evil, and your script, perhaps running as root, writes through it.

The rm does not run if the script fails, so temp files accumulate until something fills up.

mktemp

tmp=$(mktemp)
echo "$tmp"
# /tmp/tmp.8kQ2mZvX1p

ls -l "$tmp"
# -rw------- 1 colton colton 0 ... /tmp/tmp.8kQ2mZvX1p

Atomic creation, random name, mode 600. All three properties matter, and together they close the race and the symlink attack.

# a directory
tmpdir=$(mktemp -d)

# a recognisable name, for debugging
tmp=$(mktemp -t myjob.XXXXXXXX)

# somewhere specific, which matters for large files
tmp=$(mktemp -p /var/tmp myjob.XXXXXXXX)

# just the name, without creating it, which reintroduces the race
mktemp -u    # avoid this

-u prints a name without creating the file, which is exactly the race condition mktemp exists to prevent. There is almost never a good reason.

-p /var/tmp for large files. /tmp is frequently a tmpfs, so a multi-gigabyte temp file is consuming RAM. Our /tmp guide covers the distinction, and systemd-tmpfiles covers the ageing that eventually removes what you leave behind.

Cleanup that actually runs

#!/usr/bin/env bash
set -euo pipefail

tmpdir=$(mktemp -d)
cleanup() { rm -rf "$tmpdir"; }
trap cleanup EXIT

# work in "$tmpdir"

trap ... EXIT is the one that matters. It runs on normal exit, on set -e aborting, and on SIGTERM and SIGINT after their handlers.

# the common mistake: only catching signals
trap cleanup INT TERM        # misses the script simply failing
trap cleanup EXIT INT TERM   # redundant but harmless

For a script that might be killed with SIGKILL, nothing can run, which is why temp files in a directory subject to ageing is the backstop rather than the plan.

Our trap guide covers the signals, and our error handling guide covers set -euo pipefail.

Several temp files

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

out="$tmpdir/output"
err="$tmpdir/errors"
staging="$tmpdir/staging"
mkdir -p "$staging"

One temp directory, several files inside it. One trap, one rm -rf, and no chance of missing one.

Writing a file atomically

A related pattern worth having.

# wrong: a reader can see a half-written file
generate_config > /etc/myapp.conf

# right: write elsewhere, then rename
tmp=$(mktemp -p /etc myapp.conf.XXXXXX)
generate_config > "$tmp"
chmod 644 "$tmp"
mv "$tmp" /etc/myapp.conf

mv within the same filesystem is atomic. A reader sees either the old file or the new one, never a partial write. This matters for config files a running service might reload, and it is why -p /etc is there: mv across filesystems is a copy and is not atomic.

Note that mktemp creates with mode 600, so the chmod is needed if the final file should be readable.

# and flush to disk if it genuinely must survive a crash
sync -f /etc/myapp.conf

Putting it together

#!/usr/bin/env bash
# /usr/local/bin/sync-data
set -euo pipefail

readonly LOCKFILE=/var/lock/sync-data.lock
readonly TIMEOUT=1800

# one instance only
exec 9>"$LOCKFILE"
if ! flock -n 9; then
    echo "another instance is running" >&2
    exit 0
fi

# temp space, cleaned whatever happens
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

# bounded runtime, with a grace period before SIGKILL
if ! timeout -k 30 "$TIMEOUT" rsync -a --delete \
        remote:/data/ "$tmpdir/incoming/" 2>"$tmpdir/err"; then
    rc=$?
    (( rc == 124 )) && echo "rsync timed out after ${TIMEOUT}s" >&2
    cat "$tmpdir/err" >&2
    exit "$rc"
fi

# atomic swap into place
rsync -a --delete "$tmpdir/incoming/" /srv/data/

Four protections, none of them more than two lines: a lock so it cannot overlap, a temp directory that is always cleaned, a timeout with a kill grace period, and errors captured so a failure is reportable rather than silent.

Run it from a systemd timer with OnFailure= pointing at a notification unit, per our server mail guide, and a job that stops working will tell you.

Frequently Asked Questions

Why does my cron job sometimes run twice at the same time?

Because cron starts it on schedule regardless of whether the previous run finished. A job scheduled every five minutes that occasionally takes six will overlap. flock on a lock file makes the second instance either wait or exit, which is what you want.

What is wrong with using a PID file for locking?

A PID file is not atomic, so two processes can both check, both find it absent, and both create it. It also goes stale when a process is killed, leaving a lock nobody holds. flock uses a kernel lock that is released automatically when the process exits, however it exits.

Why should I use mktemp instead of a fixed filename in /tmp?

Because /tmp is world-writable, so an attacker who can predict the name can create a symlink there first and have your script write through it to a file you did not intend. mktemp creates the file atomically with a random name and mode 600, which closes both the race and the symlink attack.

What is the difference between flock -n and flock -w?

The -n option fails immediately if the lock is held, which suits a scheduled job where a second run is pointless. The -w option waits up to a given number of seconds before giving up, which suits work that must happen but can be delayed.

Do I need to delete the lock file afterwards?

No, and you should not. The lock is on the open file descriptor rather than the file existing, so the kernel releases it when the process exits. Deleting the file creates a race where another process can lock a new file with the same name while you still hold the old one.

How do I make sure my temp files are cleaned up even if the script fails?

Set a trap on EXIT that removes them, which runs whether the script ends normally, errors out under set -e, or is terminated. Trapping only INT and TERM misses the common case of the script simply failing.