check for killing ourself
authorIan Kelling <iank@fsf.org>
Tue, 2 Apr 2019 18:39:26 +0000 (14:39 -0400)
committerIan Kelling <iank@fsf.org>
Tue, 2 Apr 2019 18:39:26 +0000 (14:39 -0400)
mount-latest-subvol

index 215b07f8faf0f73ef227005ae693b17f626caf9d..2ebcca04be243ec5497ce5cc330444c1ed7e9db4 100644 (file)
@@ -15,8 +15,7 @@
 
 # usage: mount-latest-subvol
 
-# TODO, check our current directory, make sure we arent going to kill ourselves
-
+cd /
 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
 
 errcatch() {
@@ -83,6 +82,17 @@ fstab() {
     tu /etc/fstab <<<"$l"
   done
 }
+pid-check() {
+  for p in ${pids}; do
+    for m in ${my_pids[@]}; do
+      if (( p == m )); then
+        echo "$0: error: pids to kill includes our pid or a parent" >&2
+        ps -f -p $p
+        exit 1
+      fi
+    done
+  done
+}
 kill-dir() {
   for sig; do
     echo kill-dir $sig
@@ -90,11 +100,13 @@ kill-dir() {
     if pids=$(timeout 4 lsof -t $dir); then
       found_pids=true
       timeout 4 lsof -w $dir
+      pid-check
       kill -$sig $pids
     fi
     # fuser will find open sockets that lsof won't, for example from gpg-agent.
     # note: -v shows kernel processes, which then doesn't return true when we want
-    if timeout 4 fuser -m $dir &>/dev/null; then
+    if pids=$(timeout 4 fuser -m $dir 2>/dev/null); then
+      pid-check
       found_pids=true
       fuser -$sig -mvk $dir
     fi
@@ -148,6 +160,20 @@ EOF
 fi
 ##### end setup fstab for subvols we care about ######
 
+# get pids that this program depends on so we dont kill them
+my_pids=($$ $PPID)
+loop_limit=30
+count=0
+while [[ ${my_pids[-1]} != 1 && ${my_pids[-1]} != ${my_pids[-2]} && $count -lt $loop_limit  ]]; do
+  count=$((count + 1))
+  p=$(ps -p ${my_pids[-1]} -o ppid=)
+  if [[ $p == 0 || ! $p ]]; then
+    break
+  fi
+  my_pids+=($p)
+done
+
+
 for vol in q a o i; do
   d=/$vol
   if ! awk '{print $2}' /etc/fstab | grep -xF $d &>/dev/null; then