This commit is contained in:
Urban Modig
2025-10-01 10:39:23 +02:00
parent 5a4434ce0d
commit 5c5a15ea2a

View File

@ -33,19 +33,29 @@ WORKDIR=$(mktemp -d "$TMPDIR/${SCRIPT_NAME%.sh}.XXXXXX")
cleanup_tmp() { rm -rf "$WORKDIR" 2>/dev/null || true; }
# ----------------------------- lock/unlock logic ------------------------------
# Use a fixed numeric FD (200) for wider Bash compatibility (e.g., macOS bash 3.2).
LOCK_FD=200
LOCK_FILE="/tmp/${SCRIPT_NAME}.lock"
LOCK_HELD=0
lock() {
log "Creating lock… ($LOCK_FILE)"
# shellcheck disable=SC2094
exec {LOCK_FD}>"$LOCK_FILE" || die "Could not open lock file $LOCK_FILE"
if ! flock -n "$LOCK_FD"; then
exec ${LOCK_FD}>"$LOCK_FILE" || die "Could not open lock file $LOCK_FILE"
if flock -n ${LOCK_FD}; then
LOCK_HELD=1
else
die "Lock failed — another process is running."
fi
}
unlock() {
if (( LOCK_HELD )); then
log "Releasing lock…"
flock -u "$LOCK_FD" || true
flock -u ${LOCK_FD} || true
# Close the FD to avoid lingering descriptors
exec ${LOCK_FD}>&- || true
LOCK_HELD=0
fi
}
# Always cleanup on exit/interrupt