flock: как предотвратить одновременный запуск резервного копирования
Проверяем на изолированном стенде, как flock останавливает второй запуск резервного копирования, чем конфликт блокировки отличается от ошибки команды и почему оставшийся файл блокировки ещё ничего не доказывает.

В этой статье
Резервное копирование может идти дольше обычного: вырос объём данных, замедлилось хранилище, завис сетевой маршрут. Если в этот момент cron, таймер systemd или оператор запустит ту же задачу ещё раз, два процесса начнут читать, упаковывать или выгружать одни и те же данные. Результат не обязательно повредится, но проверять нагрузку, журналы и очистку временных файлов станет сложнее.
Короткий ответ: оберните всю критическую часть задания одной эксклюзивной блокировкой flock, включите неблокирующий режим и назначьте отдельный код конфликта. Затем проверьте три события: первый запуск получил блокировку, второй во время его работы завершился с кодом конфликта, третий после освобождения блокировки снова прошёл. Ниже — такой тест с фактическим результатом.
Что именно защищает flock
Утилита flock из util-linux управляет блокировкой файла или каталога и может удерживать её на время выполнения команды. По умолчанию создаётся эксклюзивная блокировка. Параметр --nonblock заставляет второй запуск не ждать, а сразу завершиться, а --conflict-exit-code задаёт отдельный код этого события. Такое поведение описано в руководстве util-linux и в справочной странице flock(1).
Блокировка рекомендательная: она работает, только если все конкурирующие запуски используют один и тот же объект блокировки. Процесс, который обходит flock или указывает другой файл, никто не остановит. И сама блокировка не говорит, что резервная копия полная и восстанавливается — она решает только вопрос одновременного входа в критическую секцию.
На уровне ядра блокировка связана не с наличием имени файла, а с открытым файловым описанием. Она освобождается, когда закрыты относящиеся к ней дескрипторы. Поэтому существующий backup.lock нельзя считать доказательством работающего процесса. Это важное различие следует из описания flock(2).
Сначала проверим на изолированном стенде
Проверка выполнена 15 ноября 2026 года на Debian GNU/Linux 13 (trixie), ядро 6.18.57, util-linux 2.41.5 и Bash 5.2.37. Временный каталог находился на tmpfs в /tmp. Скрипт дважды дал одинаковый результат и завершился с кодом 0. Это тест локальной файловой системы, а не NFS, CIFS, cron, systemd или конкретной программы резервного копирования.
Сценарий создаёт отдельный каталог вида /tmp/flock-lab.XXXXXX. Все пути определяются внутри него. Очистка разрешена только для этого шаблона; если переменная неожиданно укажет в другое место, скрипт откажется удалять данные.
Сохраните следующий текст в файл flock-lab.sh в отдельном тестовом каталоге. Для запуска достаточно обычного пользователя с правом записи в /tmp; root не нужен. В системе должны быть установлены Bash, util-linux с утилитой flock и стандартные команды mktemp, grep, sleep, chmod, cat и rm. Сценарий ждёт строку first acquired не более пяти секунд; если первый процесс её не записал, проверка завершается ошибкой и не делает вывод о конфликте.
#!/usr/bin/env bashset -euo pipefaillab_dir="$(mktemp -d /tmp/flock-lab.XXXXXX)"lock_file="$lab_dir/backup.lock"log_file="$lab_dir/run.log"worker="$lab_dir/worker.sh"cleanup() { if [[ "$lab_dir" =~ ^/tmp/flock-lab\.[A-Za-z0-9]{6}$ ]]; then rm -rf -- "$lab_dir" else printf 'Refusing cleanup outside the lab: %s\n' "$lab_dir" >&2 fi}trap cleanup EXITcat >"$worker" <<'WORKER'#!/usr/bin/env bashset -euo pipefaillock_file="$1"log_file="$2"label="$3"hold_seconds="$4"exec 9>"$lock_file"if flock --exclusive --nonblock --conflict-exit-code 75 9; then :else lock_rc=$? if [[ "$lock_rc" -eq 75 ]]; then printf '%s conflict exit=75\n' "$label" >>"$log_file" else printf '%s lock_error exit=%s\n' "$label" "$lock_rc" >>"$log_file" fi exit "$lock_rc"fiprintf '%s acquired\n' "$label" >>"$log_file"sleep "$hold_seconds"printf '%s finished\n' "$label" >>"$log_file"WORKERchmod 700 "$worker""$worker" "$lock_file" "$log_file" first 2 &first_pid=$!ready=0for attempt in {1..50}; do if [[ -f "$log_file" ]] && grep -Fxq 'first acquired' "$log_file"; then ready=1 break fi if ! kill -0 "$first_pid" 2>/dev/null; then break fi sleep 0.1doneif [[ "$ready" -ne 1 ]]; then wait "$first_pid" || : printf '%s\n' 'First worker did not report lock acquisition in time' >&2 exit 1fiset +e"$worker" "$lock_file" "$log_file" second 0second_rc=$?set -ewait "$first_pid""$worker" "$lock_file" "$log_file" third 0third_rc=$?set +eflock --exclusive --nonblock --conflict-exit-code 75 "$lock_file" /bin/sh -c 'exit 23'child_rc=$?set -eprintf 'second_rc=%s\n' "$second_rc"printf 'third_rc=%s\n' "$third_rc"printf 'child_rc=%s\n' "$child_rc"printf 'lock_file_exists=%s\n' "$([[ -e "$lock_file" ]] && printf yes || printf no)"printf '%s\n' '--- log ---'cat "$log_file"[[ "$second_rc" -eq 75 ]][[ "$third_rc" -eq 0 ]][[ "$child_rc" -eq 23 ]]grep -Fxq 'first acquired' "$log_file"grep -Fxq 'second conflict exit=75' "$log_file"grep -Fxq 'first finished' "$log_file"grep -Fxq 'third acquired' "$log_file"grep -Fxq 'third finished' "$log_file"
Проверка синтаксиса и запуск:
bash -n flock-lab.shbash flock-lab.sh
Как читать результат
В двух последовательных запусках наблюдался один и тот же вывод:
second_rc=75third_rc=0child_rc=23lock_file_exists=yes--- log ---first acquiredsecond conflict exit=75first finishedthird acquiredthird finished
Событие | Наблюдение | Вывод |
|---|---|---|
A: first | получил блокировку и работал 2 секунды | критическая секция занята |
B: second | завершился с кодом 75 | в критическую секцию не вошёл |
C: third | после завершения A вернул 0 | блокировка освобождена |
Команда с exit 23 | flock вернул 23 | код обёрнутой команды сохранён |

Строки журнала важнее одного кода: между first acquired и first finished есть second conflict exit=75, но нет second acquired. После first finished появляется third acquired. То есть второй процесс действительно не вошёл в защищённый участок, а третий вошёл после освобождения.
Строка lock_file_exists=yes не является ошибкой. Файл блокировки остался, но третий процесс успешно его заблокировал. Удалять такой файл «на всякий случай» не требуется: наличие файла и удержание блокировки — разные состояния.
Конфликт блокировки и ошибка резервного копирования — разные события
В тесте код 75 означает только невозможность немедленно получить блокировку. Когда блокировка была свободна, команда /bin/sh -c 'exit 23' выполнилась, и flock вернул код завершения этой команды — 23. Это позволяет мониторингу различать «предыдущий запуск ещё идёт» и «сама задача завершилась ошибкой».
Но код 75 не универсален. Перед внедрением проверьте документацию вашей программы резервного копирования и сценария-обёртки. Если они уже используют 75, выберите другой свободный код в диапазоне 1–255 и зафиксируйте его в мониторинге. Иначе реальная ошибка может выглядеть как штатный конфликт запуска. Ноль не подходит: мониторинг должен отличать конфликт от успешного выполнения. Ошибку самой утилиты flock также нельзя переименовывать в конфликт: сценарий сохраняет её исходный ненулевой код и записывает отдельное событие lock_error.
Критерий приёмки: код конфликта принадлежит только блокировке, а ненулевой код самой команды резервного копирования не переписывается и не считается «ещё работает».
Как перенести проверку на настоящую задачу
Лабораторный скрипт не знает путей, учётных данных и кодов возврата вашей программы резервного копирования. Поэтому переносить нужно не его временные имена, а проверенный порядок. Я бы проводил приёмку так:
Найдите все точки запуска одной задачи: cron, таймер systemd, панель управления, ручной сценарий и внешнюю автоматизацию. Они должны использовать один и тот же механизм блокировки.
Выберите стабильный локальный файл блокировки в каталоге, куда сервисный пользователь может записывать, но посторонние пользователи не могут подменять содержимое. Не размещайте его на сетевой файловой системе без отдельного теста.
Поместите под одну блокировку полный критический участок: создание временной копии, упаковку, передачу и ту очистку, которая не должна пересекаться со вторым запуском.
Назначьте код конфликта, который не совпадает с документированными кодами команды резервного копирования. В журнале отдельно записывайте получение блокировки, конфликт, окончание и код самой команды.
В тестовой среде запустите A, пока он удерживает блокировку — B, а после окончания A — C. Проверьте не только коды, но и отсутствие действий B в каталоге назначения.
Имитируйте безопасную ошибку самой команды и убедитесь, что её код дошёл до мониторинга без подмены кодом конфликта.
Только после этого переносите расписание. Первый рабочий цикл наблюдайте по журналам и метрикам нагрузки; блокировка не заменяет контроль результата резервного копирования.
Если второй запуск должен не завершаться, а ждать, неблокирующий режим можно заменить ограниченным ожиданием. Это уже другой критерий: нужно измерить допустимое время очереди и решить, что делать после тайм-аута. Бесконечное ожидание способно скрыть зависшую предыдущую задачу.
Границы решения
NFS и CIFS/SMB могут реализовывать или эмулировать блокировки иначе; поведение зависит от ядра, сервера и параметров монтирования. Локальный тест выше этого не подтверждает.
flock не является распределённой блокировкой для нескольких серверов. Если одну задачу запускают разные узлы, нужен координатор, который видят все участники и чьи отказы отдельно обработаны.
Дочерние процессы могут наследовать открытый дескриптор и продлевать жизнь блокировки. Параметр
--closeменяет это поведение, но его нельзя включать вслепую: блокировка способна освободиться раньше фактического окончания критической работы.Процесс, который не использует тот же файл блокировки, продолжит работать. Путь к блокировке и обёртка должны быть едиными для всех точек запуска.
Блокировка не проверяет читаемость архива, полноту базы и возможность восстановления.
После защиты от параллельного запуска отдельно проверьте сам результат. Для этого проверьте RPO и RTO и выполните тестовое восстановление. Если основа копии — снимок VPS, учитывайте согласованность файлов и базы. Если архив создан с помощью tar и исходный каталог ещё доступен, можно сверить архив с исходным каталогом до очистки.
Критерии приёмочного тестирования
Проверка | Ожидаемый результат |
|---|---|
A запущен первым | получил блокировку и вошёл в критическую секцию |
B запущен во время A | не выполнил защищённую работу; вернул отдельный код конфликта |
C запущен после A | получил блокировку и завершился своим кодом |
Команда завершилась ошибкой | её код дошёл до мониторинга и не превратился в конфликт |
Файл блокировки остался | новый процесс всё равно получает свободную блокировку |
Путь находится на NFS/CIFS | поведение блокировки остаётся неподтверждённым до теста на этом конкретном монтировании |
По одному признаку выводить рано. Отдельный файл блокировки, нулевой код одного запуска или отсутствие двух процессов в момент просмотра ещё не доказывают защиту. Доказательство — воспроизводимая последовательность A/B/C, раздельные коды и журнал, в котором второй процесс не выполнял критическую работу.
Backup may take longer than usual: data volume has grown, storage has slowed, or a network route has hung. If cron, a systemd timer, or an operator launches the same task again at that moment, two processes will start reading, packaging, or offloading the same data. The result may not necessarily be corrupted, but checking load, logs, and temporary file cleanup becomes harder.
Short answer: wrap the entire critical part of the job with a single exclusive flock lock, enable non-blocking mode, and assign a distinct conflict code. Then verify three events: the first run acquires the lock, the second run exits with a conflict code while the lock is held, and the third run succeeds after the lock is released. Below is such a test with actual results.
What exactly flock protects
The flock utility from util-linux manages file or directory locking and can hold the lock for the duration of a command. By default, it creates an exclusive lock. The --nonblock parameter causes a second run to exit immediately without waiting, while --conflict-exit-code sets a distinct exit code for this event. This behavior is documented in the util-linux manual and on the flock(1) man page.
The lock is advisory: it works only if all competing processes use the same lock object. No one can stop a process that bypasses flock or points to a different file. Moreover, the lock itself does not guarantee that the backup is complete or restorable; it only addresses concurrent access to the critical section.
At the kernel level, the lock is tied not to the file name but to the open file description. It is released only when the associated file descriptors are closed. Therefore, the existing backup.lock cannot be taken as proof of a running process. This important distinction follows from the flock(2) description.
First, test on an isolated staging environment
The check was performed on November 15, 2026, on Debian GNU/Linux 13 (trixie), kernel 6.18.57, util-linux 2.41.5, and Bash 5.2.37. The temporary directory was located on tmpfs in /tmp. The script produced the same result twice and exited with code 0. This is a test of a local file system, not NFS, CIFS, cron, systemd, or a specific backup program.
The scenario creates a separate directory of the form /tmp/flock-lab.XXXXXX. All paths are defined within it. Cleanup is allowed only for this template; if the variable unexpectedly points elsewhere, the script will refuse to delete the data.
Save the following text to file flock-lab.sh in a separate test directory. To run it, a regular user with write permissions to /tmp is sufficient; root access is not required. The system must have Bash installed, util-linux with the flock utility, and standard commands mktemp, grep, sleep, chmod, cat, and rm. The script waits for the string "first acquired" for no more than five seconds; if the first process does not write it, the check fails with an error and does not conclude that a conflict occurred.
#!/usr/bin/env bashset -euo pipefaillab_dir="$(mktemp -d /tmp/flock-lab.XXXXXX)"lock_file="$lab_dir/backup.lock"log_file="$lab_dir/run.log"worker="$lab_dir/worker.sh"cleanup() { if [[ "$lab_dir" =~ ^/tmp/flock-lab\.[A-Za-z0-9]{6}$ ]]; then rm -rf -- "$lab_dir" else printf 'Refusing cleanup outside the lab: %s\n' "$lab_dir" >&2 fi}trap cleanup EXITcat >"$worker" <<'WORKER'#!/usr/bin/env bashset -euo pipefaillock_file="$1"log_file="$2"label="$3"hold_seconds="$4"exec 9>"$lock_file"if flock --exclusive --nonblock --conflict-exit-code 75 9; then :else lock_rc=$? if [[ "$lock_rc" -eq 75 ]]; then printf '%s conflict exit=75\n' "$label" >>"$log_file" else printf '%s lock_error exit=%s\n' "$label" "$lock_rc" >>"$log_file" fi exit "$lock_rc"fiprintf '%s acquired\n' "$label" >>"$log_file"sleep "$hold_seconds"printf '%s finished\n' "$label" >>"$log_file"WORKERchmod 700 "$worker""$worker" "$lock_file" "$log_file" first 2 &first_pid=$!ready=0for attempt in {1..50}; do if [[ -f "$log_file" ]] && grep -Fxq 'first acquired' "$log_file"; then ready=1 break fi if ! kill -0 "$first_pid" 2>/dev/null; then break fi sleep 0.1doneif [[ "$ready" -ne 1 ]]; then wait "$first_pid" || : printf '%s\n' 'First worker did not report lock acquisition in time' >&2 exit 1fiset +e"$worker" "$lock_file" "$log_file" second 0second_rc=$?set -ewait "$first_pid""$worker" "$lock_file" "$log_file" third 0third_rc=$?set +eflock --exclusive --nonblock --conflict-exit-code 75 "$lock_file" /bin/sh -c 'exit 23'child_rc=$?set -eprintf 'second_rc=%s\n' "$second_rc"printf 'third_rc=%s\n' "$third_rc"printf 'child_rc=%s\n' "$child_rc"printf 'lock_file_exists=%s\n' "$([[ -e "$lock_file" ]] && printf yes || printf no)"printf '%s\n' '--- log ---'cat "$log_file"[[ "$second_rc" -eq 75 ]][[ "$third_rc" -eq 0 ]][[ "$child_rc" -eq 23 ]]grep -Fxq 'first acquired' "$log_file"grep -Fxq 'second conflict exit=75' "$log_file"grep -Fxq 'first finished' "$log_file"grep -Fxq 'third acquired' "$log_file"grep -Fxq 'third finished' "$log_file"
Syntax check and execution:
bash -n flock-lab.shbash flock-lab.sh
How to read the result
In two sequential runs, the same output was observed:
second_rc=75third_rc=0child_rc=23lock_file_exists=yes--- log ---first acquiredsecond conflict exit=75first finishedthird acquiredthird finished
Event | Observation | Output |
|---|---|---|
A: first | acquired the lock and ran for 2 seconds | critical section is occupied |
B: second | finished with exit code 75 | did not enter the critical section |
C: third | after A completed, returned 0 | lock released |
Command with exit 23 | flock returned 23 | exit code of the wrapped command saved |

Log lines matter more than a single code: between first acquired and first finished there is second conflict exit=75, but no second acquired. After first finished, third acquired appears. In other words, the second process truly did not enter the protected section, while the third entered after it was released.
The line lock_file_exists=yes is not an error. The lock file remains, but the third process successfully locked it. Deleting such a file "just in case" is not required: the presence of a file and holding a lock are different states.
A lock conflict and a backup error are distinct events
In the test, code 75 means only that the lock could not be acquired immediately. When the lock was free, command /bin/sh -c 'exit 23' executed, and flock returned the exit code of that command — 23. This allows monitoring to distinguish between "previous run is still in progress" and "the task itself ended with an error".
Code 75 is not universal. Before deployment, check the documentation for your backup software and wrapper script. If they already use 75, choose another available code in the 1–255 range and record it in monitoring. Otherwise, a real error may appear as a standard launch conflict. Zero is not suitable: monitoring must distinguish between a conflict and successful execution. The error code from the flock utility itself must not be renamed to a conflict: the script preserves its original non-zero code and logs a separate lock_error event.
Acceptance criterion: the conflict code belongs only to the lock, and the non-zero exit code of the backup command itself is not overwritten or treated as "still running".
How to migrate the check to the actual task
The laboratory script does not know the paths, credentials, or exit codes of your backup program. Therefore, you must migrate not its temporary names, but the verified sequence. I would conduct acceptance testing as follows:
Find all entry points for a single task: cron, systemd timer, control panel, manual script, and external automation. They must all use the same locking mechanism.
Select a stable local lock file in a directory where the service user can write but external users cannot replace its contents. Do not place it on a network file system without separate testing.
Place the entire critical section under a single lock: creating a temporary copy, packaging, transferring, and the cleanup that must not overlap with a second run.
Assign a conflict code that does not match the documented codes of the backup command. Log the lock acquisition, conflict, completion, and the command code separately.
In the test environment, run A while it holds the lock, then run B, and after A finishes, run C. Verify not only the codes but also the absence of B actions in the destination directory.
Simulate a safe error from the command itself and ensure its code reaches monitoring without being replaced by the conflict code.
Only then migrate the schedule. Monitor the first operational cycle via logs and load metrics; the lock does not replace control over the backup result.
If the second launch should not terminate but wait, the non-blocking mode can be replaced with a limited wait. This is a different criterion: you must measure the allowable queue time and decide what to do after the timeout. An infinite wait can hide a hung previous task.
Solution boundaries
NFS and CIFS/SMB may implement or emulate locks differently; behavior depends on the kernel, server, and mount parameters. The local test above does not confirm this.
flock is not a distributed lock for multiple servers. If different nodes run the same task, a coordinator is required that all participants can see and whose failures are handled separately.
Child processes may inherit an open file descriptor and extend the lock's lifetime. The
--closeparameter changes this behavior, but it must not be enabled blindly: the lock can be released before the critical work is actually finished.A process that does not use the same lock file will continue running. The lock path and wrapper must be identical for all launch points.
The lock does not verify archive readability, database completeness, or the ability to restore.
After protecting against parallel launches, separately verify the result itself. For this, check RPO and RTO and perform a test restore. If the copy base is a VPS snapshot, consider file and database consistency. If the archive was created with tar and the source directory is still accessible, you can compare the archive with the source directory before cleanup.
Acceptance testing criteria
Check | Expected result |
|---|---|
A started first | acquired the lock and entered the critical section |
B started while A was running | did not execute the protected work; returned a separate conflict code |
C started after A | acquired the lock and exited with its own code |
the command failed | its code reached monitoring and did not turn into a conflict |
the lock file remained | the new process still acquires a free lock |
The path is on NFS/CIFS | lock behavior remains unconfirmed until tested on this specific mount |
It is premature to draw conclusions based on a single indicator. A separate lock file, a zero exit code from a single run, or the absence of two processes at the moment of inspection do not prove protection. Proof requires a reproducible A/B/C sequence, distinct exit codes, and a log showing that the second process did not perform critical work.





Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.