Exclusive batch jobs on dedicated servers: testing flock lifetime

Exclusive batch jobs on dedicated servers: testing flock lifetime

Exclusive batch jobs on dedicated servers: testing flock lifetime

The overnight report is still running when someone starts a manual rerun. Both processes read the same inputs and eventually overwrite the output file at the same time. For batch-job mutual exclusion on a dedicated server, the first requirement is to ensure that only one instance of a job can run—not to guess whether it is running from a process name. This walkthrough tests flock in a local temporary directory without changing system services or touching business data.

Define the lock scope and test boundaries

A lock should represent a business resource, such as “daily summary output,” rather than a launch method. Scheduled runs, manual reruns, and failure retries must all use the same script and the same lock path. If a manual run bypasses that entry point, the lock cannot constrain the other process.

The examples below use Debian 13 and require Bash and the flock utility provided by util-linux. First, run command -v bash flock to confirm that both tools are available. Keep the test lock on the local filesystem, not in a network share; locking semantics on shared filesystems require separate verification.

After paying for an HttpAmd dedicated server, retrieve its credentials from the control panel and connect to Linux over SSH. If multiple addresses are listed, use the first one. The following commands can run under a regular account without elevated privileges.

flock provides cooperative locking. It does not prevent programs that have not acquired the same lock from modifying files, nor does it provide business transactions, result deduplication, or coordination across hosts.

“Run the job only once” also has two distinct layers: locking prevents overlapping execution, while idempotency prevents repeated side effects from successive retries. Operations such as sending messages or calling external APIs still need a unique business key or an idempotency record.

Create a single entry point and preserve the contention exit code

In the first terminal, create a private test directory and note the absolute path it prints. You will switch to that exact path in the second terminal later.

LAB=$(mktemp -d /tmp/flock-lab.XXXXXX)
chmod 700 "$LAB"
cd "$LAB"
printf '%s\n' "$LAB"

cat > run.sh <<'BASH'
set -u
cd -- "$(dirname -- "$0")" || exit 70
exec 9>>job.lock || exit 73
flock -n -E 75 9
rc=$?
if [ "$rc" -ne 0 ]; then
    printf 'lock-not-acquired rc=%s\n' "$rc" >&2
    exit "$rc"
fi
printf 'started pid=%s\n' "$$"
sleep 20
printf 'finished pid=%s\n' "$$"
BASH

bash ./run.sh

The 20 seconds here simply keep the test running long enough to hold the lock; they do not represent the job’s actual runtime. File descriptor 9 opens the lock file. Once flock succeeds, the Bash process running the script keeps that descriptor open even after the lock-acquisition command returns, so the lock remains held.

The -n option returns immediately on contention, and -E 75 sets the contention exit code to 75. For other errors, preserve the status returned by the utility rather than interpreting every failure as “a job is already running.” The script deliberately omits set -e so it can capture the acquisition result explicitly and handle each category separately.

When integrating this into a real job, replace sleep 20 with the foreground business command, capture its exit code, and exit with that same status. The scheduler should record contention skips, failures to open the lock file, and job execution failures separately instead of treating every nonzero status as the same alert.

Test rejection and re-entry with two terminals

While the first terminal shows started but has not yet shown finished, switch to the directory printed earlier in the second terminal and run:

bash ./run.sh
rc=$?
printf 'exit=%s\n' "$rc"

The second run should return lock-not-acquired rc=75 without printing a second started line. If the first run has already finished, this run will acquire the lock normally. That means the test did not overlap; it is not evidence that contention rejection failed.

After the first run prints finished, another run should enter normally. During acceptance testing, record both runs’ output and exit codes rather than checking only whether the lock file still exists. It is normal for job.lock to remain in the directory; the next run can simply open it again.

Keep the scheduled entry point consistent

For production, place the entry point in a stable directory. Keep the lock in a directory owned by the job account where other accounts cannot replace the file. Scheduled and manual runs must call that same entry point rather than construct their own lock names. Prefer explicit absolute paths so that a change in working directory cannot create two separate locks.

If the same host has containers or separate mount namespaces, identical path strings may still resolve to different files. Check the actual mounts and file identities; “same name” does not necessarily mean “same lock object.”

Check abnormal termination and descriptor inheritance

Run the test script again. During the sleep stage, use another terminal to send TERM to the printed Bash PID. Note that PID, then run the following commands, entering its actual value into the variable:

read -r -p 'Bash PID: ' RUN_PID
kill -TERM "$RUN_PID"
bash ./run.sh

Bash exiting does not necessarily release the lock immediately. The child process, sleep, inherited file descriptor 9. As long as it still holds that open file descriptor, new runs may continue to be rejected. Once the test child process exits, another run should be able to enter.

This is not a “leftover lock file”: a process still holds the lock. Use lslocks to help inspect the situation alongside the original job’s process tree. A single PID in the tool’s output is not enough to describe the entire inheritance relationship.

A production script should wait in the foreground until all work requiring mutual exclusion has finished. If a job starts a background child and returns immediately, you must establish who keeps holding the lock and who waits for the child to exit. A child that genuinely does not belong to the protected work can close its descriptor 9 when it starts. Do not, however, arbitrarily close the lock descriptor in the actual business process, or a second run could be admitted too soon.

Avoid deleting locks to unlock jobs, and build a production checklist

The most dangerous repair is to run rm job.lock after discovering that a job is stuck. The old process continues to hold a lock on the old inode, while a new process can create a file with the same name and lock the new inode. Both may then enter the business-critical section at once. Restoring the filename does not restore mutual exclusion.

For the same reason, do not let cleanup scripts, deployment switches, or temporary-directory cleanup mechanisms replace a lock file that is in use. A temporary directory is fine for this test. Production needs a stable, protected lock directory whose lifecycle is independent of individual deployments.

Before going live, verify at least the following:

Clean up the test directory only after the test is complete and every process has exited. The resulting operating rules should be simple: one entry point, a stable lock object, meaningful exit codes, and clear responsibility for child processes. With those four conditions met, mutual exclusion becomes a verified execution contract rather than just an extra command at the top of a script.

Frequently asked questions

Should the lock file be deleted after a job exits?

No. The flock lock is associated with open file descriptors, not with the file's mere existence. It is released when the last descriptor holding it closes. Deleting the file during a run can let another process lock a different inode and execute concurrently.

Does this prevent duplicate execution across multiple servers?

This guide validates cooperating processes on one server's local file system. Multiple servers require a separate coordination design. External API calls, payments, and message delivery also need idempotency keys or business-level uniqueness constraints.

AMD EPYC 7543P Dedicated Server

HttpAmd From $470.5/month

Review the server specifications

Compare the memory, direct-attached NVMe, bandwidth, and IPv4 specifications, then confirm the amount due for the current billing period on the configuration page.