PREP WITH PROOF
Menu
IT INFRASTRUCTURE / PRACTICAL GUIDE

Linux flock: Prevent Overlapping Jobs Without Deleting Locks

Use flock to skip or wait for overlapping Linux jobs. Test lock lifetime, inherited descriptors, and why deleting a lock file can break mutual exclusion.

THE QUICK ANSWER

Wrap cooperating Linux jobs with flock and choose a nonblocking or bounded-wait acquisition policy. Keep the lock file stable: deleting and recreating its path can let another process lock a different file while the original holder still runs.

A schedule does not guarantee one running instance

A data import normally finishes in three minutes, so it runs every five minutes. One slow dependency stretches an execution to twelve minutes. The next invocation starts while the first is still writing, and both processes claim the same input. Increasing the schedule interval can reduce the chance of overlap, but it does not enforce mutual exclusion.

On Linux, flock can hold an advisory lock while a command runs. Every cooperating invocation must use the same lock object and respect failure to acquire it. The mere existence of a file called job.lock is not an indication that a process holds a kernel lock on it. Conversely, an empty file can be actively locked.

Decide what a second invocation should do. It can skip immediately, wait for a bounded time, or wait indefinitely. Those policies have different operational consequences. A scheduled import may prefer skipping with a visible status; a manually requested maintenance operation might prefer a short wait.

Source: util-linux flock: command forms, wait policy and descriptor options ↗

Choose skip or wait deliberately

The command form wraps an exclusive lock around the child command. With -n, acquisition is nonblocking. The example selects exit code 75 for lock contention using -E. Replace the lock path and executable with your own approved paths. Provision a directory the service account can use, protected from untrusted replacement of lock files.

Without -n or -w, flock waits until the lock becomes available. That can create a growing queue of scheduled invocations rather than solving an overloaded job. With -w 30, acquisition waits for up to thirty seconds. The wait allowance is not a runtime timeout for the command after it starts.

The command's exit status is normally returned when it runs. Choose a contention code your workload does not use for an unrelated failure, or log the acquisition outcome separately. If the child itself returns 75, an external observer cannot distinguish that from the configured lock-conflict status using the number alone. Keep skipped invocations visible rather than treating all nonzero results as successful work.

# Skip immediately if another cooperating execution holds the lock.
flock -n -E 75 /run/lock/example-import.lock /usr/local/bin/example-import

# Alternatively, wait up to 30 seconds to acquire it.
flock -w 30 -E 75 /run/lock/example-import.lock /usr/local/bin/example-import

Source: util-linux flock: command forms, wait policy and descriptor options ↗

The lock belongs to an open file description

For flock(2), locks are associated with an open file description. Duplicated or inherited descriptors can refer to the same description. The lock is released by an explicit unlock on an associated descriptor or when all descriptors referring to that description are closed. This is a different lifetime from a pathname in a directory.

That distinction explains two practical surprises. First, a file left on disk after the process exits need not be a stale lock. Opening that same file and successfully acquiring the lock is what matters. Second, a descendant that inherits a descriptor can keep the lock alive after the original process exits.

Keep the protected workload in the foreground and understand which processes remain. A wrapper that launches the real job in the background and immediately exits can provide a different lock lifetime from the one you intended. The command-form --close option closes the lock descriptor in the executed child while the flock parent holds it. That can prevent unintended inheritance, but it is not a substitute for waiting for the actual protected work. It is incompatible with --no-fork.

Source: Linux flock(2): open file descriptions and filesystem behavior ↗

Do not use deletion as the normal unlock operation

Suppose process A opens job.lock and locks it. An administrator removes that path because the file looks old. A still has an open reference to the original file. Process B then opens job.lock with creation enabled, gets a new file, and acquires a lock on that new object. Both can now believe they are the exclusive runner.

Keeping the same pathname therefore is not enough if the file is removed and replaced. Use a stable file in a controlled directory, leave it in place between runs, and let the lock lifetime follow the open descriptors. Avoid routine cleanup that deletes the lock file at the end of every job; it introduces a race with other invocations.

When diagnosing apparent contention, identify the holder and its process tree through appropriate tools and permissions. Utilities such as lslocks or lsof can help locate candidate processes, but take a fresh observation before acting because processes and descriptors change. Coordinate with the owning service to finish, cancel or restart the protected work according to its recovery procedure. Removing the pathname is not a way to make that work stop.

Source: Linux flock(2): open file descriptions and filesystem behavior ↗

Reproduce the pathname replacement problem safely

Run the following Python script on Linux. It creates a temporary lock file and invokes independent Python processes that attempt a nonblocking exclusive flock. It does not touch service files or a system lock directory. The assertions check both normal release and the unsafe deletion pattern.

The first child cannot acquire the file while the parent holds it. After the parent closes its descriptor, another child can acquire the same file. The final case deliberately unlinks the path while the parent holds its lock, then confirms that a child can lock a replacement file with a different inode.

The script uses Python fcntl.flock to exercise the same Linux locking mechanism. It was run with Python 3.12, and the command-line examples were separately checked with util-linux flock 2.41.5. The deletion occurs only inside the temporary fixture; do not adapt that step into production cleanup.

import fcntl
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory

probe = r"""
import errno, fcntl, json, os, sys
with open(sys.argv[1], "a+") as stream:
    try:
        fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError as exc:
        if exc.errno in (errno.EAGAIN, errno.EACCES):
            sys.exit(75)
        raise
    print(json.dumps({"locked": True, "inode": os.fstat(stream.fileno()).st_ino}))
"""

def try_lock(path):
    return subprocess.run(
        [sys.executable, "-c", probe, str(path)],
        capture_output=True, text=True, timeout=5, check=False,
    )

with TemporaryDirectory(prefix="flock-demo-") as tmp:
    path = Path(tmp) / "job.lock"
    with path.open("a+") as holder:
        fcntl.flock(holder, fcntl.LOCK_EX)
        first = os.fstat(holder.fileno())
        busy = try_lock(path)
        assert busy.returncode == 75, busy.stderr
        print("same path and file: second process cannot acquire")

    available = try_lock(path)
    assert available.returncode == 0, available.stderr
    print("holder closed: second process can acquire the same file")

    with path.open("a+") as holder:
        fcntl.flock(holder, fcntl.LOCK_EX)
        first = os.fstat(holder.fileno())
        # Deliberately unsafe pattern, only inside this temporary lab.
        path.unlink()
        assert os.fstat(holder.fileno()).st_nlink == 0
        replacement = try_lock(path)
        assert replacement.returncode == 0, replacement.stderr
        other = json.loads(replacement.stdout)
        assert other["inode"] != first.st_ino
        print("deleted and recreated path: second process acquired a different file")

        # The holder still owns the original open file until this context exits.
        assert os.fstat(holder.fileno()).st_ino == first.st_ino

Source: Python fcntl: flock and nonblocking operation ↗

What the three assertions establish

The first result proves that two cooperating processes contend on the same local file. The second proves that closing the holder permits a later acquisition of that file. The third proves that a pathname can refer to a different file while the original locked file is still open. A lock cannot coordinate callers that silently stop using the same object.

These checks do not prove crash recovery of the import itself. A process can release its lock by exiting after a partial database write or half-finished file operation. If the next invocation retries, it still needs an application-level recovery and idempotency policy. Mutual exclusion prevents simultaneous cooperating executions; it does not make interrupted business work complete or safe to repeat.

same path and file: second process cannot acquire
holder closed: second process can acquire the same file
deleted and recreated path: second process acquired a different file

Source: Linux flock(2): open file descriptions and filesystem behavior ↗

Check filesystem and deployment boundaries

A local file lock is not automatically a distributed lease. Two containers can use identical path strings while each sees its own filesystem object. Two hosts with separate local disks cannot coordinate through a shared-looking /run/lock path. If you use a shared filesystem, verify the locking semantics of that actual filesystem, server, kernel and mount configuration.

Linux behavior over NFS and SMB has version- and protocol-dependent details. The flock manual documents differences, including interactions with other lock types and possible mandatory effects on SMB. Test a real two-client acquisition and failure scenario on the intended storage before relying on it. Do not assume that a local temporary-directory test establishes remote behavior.

All writers must participate. A manual invocation of the import executable that bypasses the wrapper can overlap the scheduled one. Place acquisition at an entry point all cooperating executions use, or enforce the invariant through the appropriate shared application system. If the deployment needs multiple hosts to process a queue, a local single-runner lock may be the wrong coordination scope.

Source: Linux flock(2): open file descriptions and filesystem behavior ↗

Verify the behavior users will observe

For the actual job, start a controlled long execution and trigger a second invocation through the supported entry point. Check whether it skips or waits as intended, which status is recorded, and whether the protected work continues in the foreground. Repeat a normal completion and a controlled failure to confirm that another invocation can later acquire the lock.

Record skipped runs separately from successful imports. A persistent stream of skips can indicate that a job is consistently slower than its schedule, even when mutual exclusion is working perfectly. Investigate queue age and completion rates instead of adding another lock or increasing an indefinite waiting queue.

A useful lock design is small: one agreed object, one acquisition policy, and a lifetime that matches the work. Keep the pathname stable, inspect the actual holder when something appears stuck, and verify the interrupted job’s recovery independently from the lock.

Source: util-linux flock: command forms, wait policy and descriptor options ↗

KEEP THESE THREE THINGS

Your next steps

  1. Choose skip or bounded wait explicitly, and distinguish contention from job failure.
  2. Let descriptor lifetime release the lock; do not routinely delete the lock pathname.
  3. Test coordination and interrupted-work recovery at the actual filesystem and deployment scope.

Sources & official resources

Linked resources checked on 2026-11-12. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →