Flock Mutex Critical Section

Prevent concurrent script runs with flock on a lockfile, distinguishing owner from contenders and timing out politely.

BashResilience

Code

bashsnippet
31 lines
#!/usr/bin/env bash
set -euo pipefail

readonly LOCK_FILE="/tmp/nightly-sync.lock"
readonly LOCK_WAIT=5

# 形态一:非阻塞抢锁,拿不到直接退出(调度器友好)
exec 9>"${LOCK_FILE}"
if ! flock -n 9; then
  echo "另一实例正在运行,跳过本次执行" >&2
  exit 0
fi

# 形态二:限时等待锁(需要排队的场景)
# flock -w "${LOCK_WAIT}" 9 || { echo "锁等待超时" >&2; exit 75; }

echo "获得锁,PID $$ 开始同步"

critical_section() {
  local started=$(date +%s)
  # ... 同步主体,异常退出时锁随文件描述符自动释放 ...
  sleep 2
  echo "同步完成,耗时 $(( $(date +%s) - started ))s"
}

critical_section

# 拿到锁后派生的后台任务也持锁,需要先关描述符
exec 9>&-
echo "锁已释放,脚本结束"

How it works

set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.

The work is delegated to readonly, exec and sleep, chained through 2 pipes so each stage’s output feeds the next.

A helper function (critical_section) keeps the repeated logic out of the main flow.

The key statements, annotated

exec 9>"${LOCK_FILE}"
local started=$(date +%s)

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `exec`, `sleep` must be available on the PATH environment variable; everything else is shell built-in syntax.