Skip to content

Instantly share code, notes, and snippets.

@aofei
Last active August 18, 2024 16:02
Show Gist options
  • Save aofei/b96eedf4edd45012d8bdc6ae2ee1327d to your computer and use it in GitHub Desktop.
Save aofei/b96eedf4edd45012d8bdc6ae2ee1327d to your computer and use it in GitHub Desktop.
A shell script for supervising and keeping processes alive.
#!/bin/sh
set -e
if [[ "$#" -lt 2 || ! -x "$2" ]]; then
echo "Usage: supervise log_tag program [program-argument...]" >&2
exit 2
fi
LOG_TAG="$1"
shift
set +e -o pipefail
while true; do
STARTED_AT="$(date +%s)"
"$@" 2>&1 | logger -t "${LOG_TAG}[$(pgrep -oP "$$")]"
EXIT_CODE="$?"
for CODE in 0 137 143; do [[ "${CODE}" -eq "${EXIT_CODE}" ]] && exit 0; done
[[ "$(($(date +%s)-${STARTED_AT}))" -gt 5 ]] && sleep 0.1 || sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment