From 0b86ad6af8721216959da4b3194c4ab3208c1ada Mon Sep 17 00:00:00 2001 From: =?utf8?q?Paul=20H=C3=A4nsch?= Date: Mon, 23 Aug 2021 15:22:53 +0200 Subject: [PATCH] experimental lock algorithm --- cgilite/storage.sh | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/cgilite/storage.sh b/cgilite/storage.sh index 61eec88..c0f9076 100755 --- a/cgilite/storage.sh +++ b/cgilite/storage.sh @@ -28,38 +28,40 @@ LOCK(){ local lock timeout block lock="${1}.lock" timeout="${2-20}" - if [ \! -w "${lock%/*}" ] || [ -e "$lock" -a \! -d "$lock" ]; then + + if [ \! -w "${lock%/*}" ] || [ -e "$lock" -a \! -f "$lock" ]; then debug "Impossible to get lock: $lock" return 1 fi - while ! mkdir "$lock" 2>&-; do - block="$(cat "$lock/pid" || printf 1)" - if ! { ps -eo pid |grep -qwF "$block"; }; then + while [ $timeout -gt 0 ]; do + printf '%i\n' $$ >>"${lock}" + read block <"$lock" + if [ "$block" = $$ ]; then + return 0 + elif ! { ps -eo pid |grep -qwF "$block"; }; then debug "Overriding stale lock: $lock" - break - fi - if [ $timeout -le 0 ]; then - debug "Timeout while trying to get lock: $lock" - return 1 + if LOCK "$lock" 1; then + rm -- "$lock" + RELEASE "$lock" + fi + else + timeout=$((timeout - 1)) + sleep 1 fi - timeout=$((timeout - 1)) - sleep 1 done - printf '%i\n' $$ >"${lock}/pid" - return 0 + + debug "Timeout while trying to get lock: $lock" + return 1 } RELEASE(){ - local lock + local lock block lock="${1}.lock" - if [ "$(cat "$lock/pid")" = "$$" ]; then - rm "$lock/pid" - if ! rmdir "$lock"; then - debug "Cannot remove tainted lock: $lock" - printf '%i\n' $$ >"${lock}/pid" - return 1 - fi + + read block <"$lock" + if [ "$block" = $$ ]; then + rm -- "$lock" return 0 else debug "Refusing to release foreign lock: $lock" -- 2.39.2