Skip to content

Instantly share code, notes, and snippets.

@hongkongkiwi
Created August 22, 2021 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongkongkiwi/fe310bf4c4d9acddafb8743b0ad02b33 to your computer and use it in GitHub Desktop.
Save hongkongkiwi/fe310bf4c4d9acddafb8743b0ad02b33 to your computer and use it in GitHub Desktop.
A simple app wrapper script which uses https://github.com/xiezhenye/waitpid to wait for the pid to and handles termination of the app if the script terminates. Call the script with ./app-wrapper syslogd <args>
#!/bin/sh
BIN="$1"; shift
[ -z "$BIN" ] && { echo >&2 "ERROR: no app passed"; exit 1; }
APP_NAME=$(basename "$BIN")
PID_FILE=${PID_FILE:-"/var/run/${APP_NAME}.pid"}
function killapp() { [ -n "$APP_PID" ] && kill -s TERM $APP_PID 2>/dev/null >/dev/nulll; }
trap killapp INT TERM SIGTERM EXIT
rm -f "$PID_FILE" 2>/dev/null
APP_DIR=$(dirname "$BIN")
CUR_DIR="$PWD"
cd "$APP_DIR"
PATH="$APP_DIR:$PATH"
"$APP_NAME" $@
cd "$CUR_DIR"
APP_PID=$(pidof -s "$APP_NAME")
echo "$APP_PID" > "$PID_FILE"
# Wait for app to complete
waitpid $APP_PID
EXIT_CODE=$?
# Remove pid after use
rm -f "$PID_FILE" 2>/dev/null
exit $EXIT_CODE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment