Skip to content

Commit

Permalink
Kill orphaned processes before destroying chroot
Browse files Browse the repository at this point in the history
Resolves #7
  • Loading branch information
jirutka committed Sep 11, 2023
1 parent 35a8732 commit 458376d
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions destroy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,28 @@ set -eo pipefail

readonly SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

# Kill all processes that have some file opened in the chroot, except this script.
echo 'Terminating remaining processes in the chroot'
if lsof -Fp -p ^$$ "$SCRIPT_DIR" | sed -n 's/^p//p' | xargs -r kill; then
sleep 1

if lsof -Fp -p ^$$ "$SCRIPT_DIR" >/dev/null; then
echo 'Waiting 5 sec for processes to terminate before killing them...'
sleep 5
lsof -Fp -p ^$$ "$SCRIPT_DIR" | sed -n 's/^p//p' | xargs -r kill -SIGKILL
fi
fi

# Unmounts all filesystem under the specified directory tree.
cat /proc/mounts | cut -d' ' -f2 | grep "^$SCRIPT_DIR." | sort -r | while read path; do
failed=false
for path in $(cat /proc/mounts | cut -d' ' -f2 | grep "^$SCRIPT_DIR." | sort -r); do
echo "Unmounting $path"
umount -fn "$path" || exit 1
umount -fn "$path" || failed=true
done

echo "Removing $SCRIPT_DIR" >&2
rm -rf --one-file-system "$SCRIPT_DIR"
if $failed; then
echo "Skipping removal of $SCRIPT_DIR due to previous error(s)" >&2
else
echo "Removing $SCRIPT_DIR" >&2
rm -rf --one-file-system "$SCRIPT_DIR"
fi

0 comments on commit 458376d

Please sign in to comment.