Skip to content

Instantly share code, notes, and snippets.

@leopoldodonnell
Created February 8, 2018 11:09
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 leopoldodonnell/ae1b703454ce4e326082e86f46a5907d to your computer and use it in GitHub Desktop.
Save leopoldodonnell/ae1b703454ce4e326082e86f46a5907d to your computer and use it in GitHub Desktop.
A Bourne Shell script that will run a command in the background and will send it a SIGTERM when it is received
#!/bin/sh
#
# The script demonstrates how to terminate a background process. It will run
# the process and wait till a SIGTERM signal is received, then it will pass that
# along to the background process and return its status.
#
# Syntax: background.sh command-line
#
pid=0
# SIGTERM-handler
term_handler() {
if [ $pid -ne 0 ]; then
kill -TERM "$pid"
wait "$pid"
exit $?
fi
}
# setup handlers
# on callback, kill the last background process, which is `tail -f /dev/null` and execute the specified handler
trap 'kill ${!}; term_handler' TERM
# run application that was passed as arguments to the script
$@ &
pid="$!"
# wait forever
while true
do
tail -f /dev/null & wait ${!}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment