aboutsummaryrefslogtreecommitdiffstats
path: root/unix
diff options
context:
space:
mode:
authorAaron LI <aly@aaronly.me>2018-04-01 01:23:31 +0800
committerAaron LI <aly@aaronly.me>2018-04-01 01:23:31 +0800
commitf0657cb84a6d3dea52cc95978c004fc8646805b1 (patch)
treebbaa4ee060bb5e71ad517159e4620ae1693a76f8 /unix
parentcc6cc01713016e5bca7a72a739836757ab01f728 (diff)
downloadatoolbox-f0657cb84a6d3dea52cc95978c004fc8646805b1.tar.bz2
Add waitpid-change.sh: Find matching PID and waiting for its change
Diffstat (limited to 'unix')
-rwxr-xr-xunix/waitpid-change.sh69
1 files changed, 69 insertions, 0 deletions
diff --git a/unix/waitpid-change.sh b/unix/waitpid-change.sh
new file mode 100755
index 0000000..92d4b7a
--- /dev/null
+++ b/unix/waitpid-change.sh
@@ -0,0 +1,69 @@
+#!/bin/sh
+#
+# Find the PID of a command and wait until it changes.
+#
+# Aaron LI
+# 2018-04-01
+#
+
+self="$0"
+
+getpid() {
+ pattern="$1"
+ output=$(ps auxww | grep "${pattern}" | grep -v grep | grep -v ${self})
+ lines=$(echo "${output}" | wc -l)
+
+ if [ ${lines} -gt 1 ]; then
+ echo "Error: multiple processes matching the pattern: '${pattern}'" >&2
+ echo
+ echo "${output}" >&2
+ exit 2
+ elif [ -z "${output}" ]; then
+ echo "Error: no processes matching the pattern: '${pattern}'" >&2
+ exit 3
+ fi
+
+ echo "${output}" | awk '{ print $2 }'
+}
+
+usage() {
+ echo "usage: ${self##*/} [-h] [-d delay] <pattern>"
+ exit 1
+}
+
+while getopts :d:h opt; do
+ case "${opt}" in
+ d)
+ delay=${OPTARG}
+ ;;
+ h)
+ usage
+ ;;
+ \?)
+ echo "Invalid option -${OPTARG}" >&2
+ usage
+ ;;
+ :)
+ echo "Option -${OPTARG} requires an argument" >&2
+ usage
+ ;;
+ esac
+done
+shift $((OPTIND - 1))
+[ $# -ne 1 ] && usage
+
+delay=${delay:-5} # [second]
+pattern="$1"
+
+pid=$(getpid "${pattern}") || exit $?
+echo "Process ${pid} matches pattern: '${pattern}'"
+echo -n "waiting for pid change ..."
+sleep ${delay}
+while pid2=$(getpid "${pattern}"); do
+ [ ${pid2} -ne ${pid} ] && {
+ echo "changed!"; exit 0
+ }
+ echo -n "."
+ sleep ${delay}
+done
+exit $?