Skip to content

Instantly share code, notes, and snippets.

@vhoyer
Last active August 15, 2022 23:28
Show Gist options
  • Save vhoyer/7130f95b830e6d302c537701ad7f83d2 to your computer and use it in GitHub Desktop.
Save vhoyer/7130f95b830e6d302c537701ad7f83d2 to your computer and use it in GitHub Desktop.
Forward TERM signal to all sub-processes

Forward TERM signal to all sub-processes

It only requires you to prepend all commands with run, then if the script process is TERM, it will forward the signal to the processes you instanciated using the run command if they are still alive, if they are not, they are just ignored.

This was designed to make docker containers shutdown faster when you have a starting script to run (in this example we are running npm install and npm start), this works because when requested to stop the container, docker will send a TERM signal to the process with id 1, which is the first command ran by the CMD (CMD ["this_command_here.sh"]).

So if this script receives TERM it will forward it leading every process to shutdown, so the container can die peacefully.

References:

#!/bin/sh
set -e
PIDS_FILE="/tmp/pids"
run() {
echo "$*" # feedback of execution
"$@" & # async execution
pid=$! # save pid
echo "$pid" >>$PIDS_FILE # store pid
wait "$pid" # await pid
}
terminate() {
# forward TERM signal to all subprocesses whose pid reside on $PIDS_FILE
xargs -f $PIDS_FILE -I{} "kill -TERM '{}' 2> /dev/null"
}
trap terminate TERM
run npm install
run npm start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment