-
Notifications
You must be signed in to change notification settings - Fork 0
/
waitfor.sh
executable file
·87 lines (78 loc) · 2.41 KB
/
waitfor.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
82
83
84
85
86
87
#!/bin/zsh -
#===============================================================================
#
# FILE: waitfor.sh
#
# USAGE: ./waitfor.sh <PID>, or
# ./waitfor.sh <process name>
#
# DESCRIPTION: waits for one process to finish without using loops.
#
# OPTIONS: None so far
# REQUIREMENTS: inotifywait installed
# EXIT CODES: 4 no PID, 5 more than one named process, 3 more than one process,
# 54 for timeout command not present, 124 for timeout elapsed
# BUGS: None so far
# NOTES: ---
# AUTHOR: Cláudio "Patola" Sampaio (Patola), [email protected]
# ORGANIZATION: MakerLinux
# CREATED: 07/18/2017 05:43:26 PM -03
# REVISION: 01
#===============================================================================
set -o nounset # Treat unset variables as an error
PROG=$0
usage() {
echo " Usage:" >&2
echo "$(basename $PROG) [-t time] <pid of process>, or" >&2
echo "$(basename $PROG) [-t time] <name of process>, or" >&2
echo "$(basename $PROG) --help" >&2
echo -e "\nWaits for one process to finish by select() instead of polling (i.e., not looping until it exits)." >&2
echo "If timeout <time> is reached, it stops waiting and exits with no error code." >&2
}
zparseopts -D -E -A Args -- t: -help
(( ${+Args[--help]} )) && {
usage
exit 0
}
TIMECMD=""
TIMEDURATION=""
(( ${+Args[-t]} )) && {
if [[ ${Args[-t]} =~ ^[0-9][0-9]*$ ]]
then
TIMECMD="/usr/bin/timeout"
TIMEDURATION="${Args[-t]}"
else
echo "Time parameter must be numeric (seconds), '${Args[-t]}' is not." >&2
usage
exit 2
fi
}
[[ $# -eq 1 ]] || {
usage
exit 3
}
[[ -x /usr/bin/timeout ]] || {
echo "This script requires the timeout command present on the system to work." >&2
echo "Please install coreutils." >&2
exit 54
}
if [[ $1 =~ ^[0-9][0-9]*$ ]] # formed only of digits
then
PID=$1
[[ -d /proc/$PID ]] || {
echo "Process with PID $PID does not exist." >&2
usage
exit 4
}
else
PID=$(/usr/bin/pgrep "$1")
[[ $(echo $PID | /usr/bin/wc -w) -gt 1 ]] && {
echo "There are $(echo $PID | wc -w ) processes with '$1' on it: $(echo $PID | sed ':a;N;$!ba;s/\n/, /g')." >&2
echo "The command requires only one process." >&2
usage
exit 5
}
fi
#/usr/bin/inotifywait -e close /proc/$PID/cgroup > /dev/null 2>&1
$TIMECMD $TIMEDURATION /usr/bin/tail -f /dev/null --pid=$PID
exit $?