1#!/bin/bash
2set -e
3
4function usage() {
5  echo "Usage: $0 <timeout seconds> <command to run on timeout>"
6  echo "Waits for up to <timeout seconds> for the parent process to exit"
7  echo "If the parent process hasn't exited in that time, runs the given command"
8  exit 1
9}
10
11waitSeconds="$1"
12shift
13runOnTimeout="$*"
14count=0
15if [ "$waitSeconds" == "" ]; then
16  usage
17fi
18if [ "$runOnTimeout" == "" ]; then
19  usage
20fi
21while true; do
22  if ! ps -f "$PPID" >/dev/null 2>/dev/null; then
23    # parent process is done, so we don't need to monitor anymore
24    exit 0
25  fi
26  sleep 1
27  count="$((count + 1))"
28  if [ "$count" -gt "$waitSeconds" ]; then
29    separator="#########################################################################################################################"
30    echo "$separator" >&2
31    echo "Parent process $PPID running longer than the expected $waitSeconds seconds. monitor.sh now running $runOnTimeout" >&2
32    echo "$separator" >&2
33    bash -c "$runOnTimeout"
34    exit 1
35  fi
36done
37