aboutsummaryrefslogtreecommitdiffstats
path: root/unix/waitpid-change.sh
blob: 92d4b7a3ca71e6694c6f9153ce1b9450cf7f9ac8 (plain)
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
#!/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 $?