Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created November 14, 2016 20:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimau/fd34c46dd9a21f4d364f47f30002df47 to your computer and use it in GitHub Desktop.
Save dansimau/fd34c46dd9a21f4d364f47f30002df47 to your computer and use it in GitHub Desktop.
process supervisor in bash
#!/bin/bash
#
# Spawn a process and restart it if it exits.
#
declare -i exit_code
declare -i pid
_cleanup() {
echo "[$(date)]: sending TERM to pid $pid"
kill -TERM $pid
exit 0
}
trap _cleanup EXIT
while true; do
echo "[$(date)]: spawning $1..."
"$@" &
pid=$!
wait $pid
exit_code=$?
echo "[$(date)]: $1 exited with code $exit_code"
sleep 1
done
@kool927
Copy link

kool927 commented Apr 8, 2020

Can you provide a manual on how to use this? I tried by creating a bash file bash.sh and then attach my program to it like bash.sh my_program.go It didn't work when I stopped the program

@dansimau
Copy link
Author

dansimau commented Apr 8, 2020

@kool927 what was the full output? How did you stop/kill the program?

@kool927
Copy link

kool927 commented Apr 8, 2020

It was printing in loop this
the program exited with code 0

@m1khal3v
Copy link

m1khal3v commented Aug 8, 2022

Replacing "$@" to /bin/bash -c "$1" works as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment