forked from ikipro/aos
-
Notifications
You must be signed in to change notification settings - Fork 2
/
umount_kill.sh
executable file
·81 lines (72 loc) · 2.44 KB
/
umount_kill.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/bin/bash -e
#
# Written by Jason Mehring ([email protected])
# Modified by Patrick Schleizer ([email protected])
#
# Kills any processes within the mounted location and
# unmounts any mounts active within.
#
# To keep the actual mount mounted, add a '/' to end
#
# $1: directory to umount
#
# Examples:
# To kill all processes and mounts within 'chroot-jessie' but keep
# 'chroot-jessie' mounted:
#
# ./umount_kill.sh chroot-jessie/
#
# To kill all processes and mounts within 'chroot-jessie' AND also
# umount 'chroot-jessie' mount:
#
# ./umount_kill.sh chroot-jessie
#
# $1 = full path to mount;
# $2 = if set will not umount; only kill processes in mount
umount_kill() {
MOUNTDIR="$1"
# We need absolute paths here so we don't kill everything
if ! [[ "$MOUNTDIR" = /* ]]; then
MOUNTDIR="${PWD}/${MOUNTDIR}"
fi
# Strip any extra trailing slashes ('/') from path if they exist
# since we are doing an exact string match on the path
MOUNTDIR=$(echo "$MOUNTDIR" | sed s#//*#/#g)
echo "-> Attempting to kill any processes still running in '$MOUNTDIR' before un-mounting"
for dir in $(grep "$MOUNTDIR" /proc/mounts | cut -f2 -d" " | sort -r | grep "^$MOUNTDIR")
do
pids=$(lsof "$dir" 2> /dev/null | \
grep "$dir" | \
tail -n +2 | \
awk '{print $2}')
if [ "$pids" = "" ]; then
echo "Okay, no pids still running in '$MOUNTDIR', no need to kill any."
else
echo "Okay, the following pids are still running inside '$MOUNTDIR', which will now be killed."
ps -p $pids
kill -9 $pids
fi
if ! [ "$2" ] && $(mountpoint -q "$dir"); then
echo "un-mounting $dir"
umount -n "$dir" 2> /dev/null || \
umount -n -l "$dir" 2> /dev/null || \
echo "umount $dir unsuccessful!"
elif ! [ "$2" ]; then
# Look for (deleted) mountpoints
echo "not a regular mount point: $dir"
base=$(basename "$dir")
dir=$(dirname "$dir")
base=$(echo "$base" | sed 's/[\].*$//')
dir="$dir/$base"
umount -v -f -n "$dir" 2> /dev/null || \
umount -v -f -n -l "$dir" 2> /dev/null || \
echo "umount $dir unsuccessful!"
fi
done
}
kill_processes_in_mount() {
umount_kill $1 "false" || :
}
if [ $(basename "$0") == "umount_kill.sh" -a "$1" ]; then
umount_kill "$1"
fi