From f0657cb84a6d3dea52cc95978c004fc8646805b1 Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Sun, 1 Apr 2018 01:23:31 +0800 Subject: Add waitpid-change.sh: Find matching PID and waiting for its change --- unix/waitpid-change.sh | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100755 unix/waitpid-change.sh 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] " + 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 $? -- cgit v1.2.2