]> git.plutz.net Git - serve0/commitdiff
Squashed 'cgilite/' changes from 38702db..07b4b96
authorPaul Hänsch <paul@plutz.net>
Mon, 23 Aug 2021 15:29:52 +0000 (17:29 +0200)
committerPaul Hänsch <paul@plutz.net>
Mon, 23 Aug 2021 15:29:52 +0000 (17:29 +0200)
07b4b96 simpler lock algorithm using files

git-subtree-dir: cgilite
git-subtree-split: 07b4b96f662c7649130701b27865a851488ee2f7

storage.sh

index 61eec88fb2cee63f706a634eaa48c85a09ef1967..77ee29c06243eae9359c03125626a46f498cded4 100755 (executable)
@@ -1,6 +1,6 @@
 #!/bin/sh
 
-# Copyright 2018, 2019 Paul Hänsch
+# Copyright 2018, 2019, 2021 Paul Hänsch
 #
 # This is a file format helper, part of CGIlite.
 # 
@@ -25,41 +25,40 @@ BR='
 '
 
 LOCK(){
-  local lock timeout block
-  lock="${1}.lock"
-  timeout="${2-20}"
-  if [ \! -w "${lock%/*}" ] || [ -e "$lock" -a \! -d "$lock" ]; then
+  local lock="${1}.lock" timeout="${2-20}" block
+
+  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
-      debug "Overriding stale lock: $lock"
-      break
-    fi
-    if [ $timeout -le 0 ]; then
-      debug "Timeout while trying to get lock: $lock"
-      return 1
+  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 "Trying to override stale lock: $lock"
+      if LOCK "$lock" 1; then
+        rm -- "$lock"
+        RELEASE "$lock"
+      fi
+    else
+      timeout=$((timeout - 1))
+      [ $timeout -gt 0 ] && 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
-  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
+  local lock="${1}.lock" block
+
+  read block <"$lock"
+  if [ "$block" = $$ ]; then
+    rm -- "$lock"
     return 0
   else
     debug "Refusing to release foreign lock: $lock"