Gracefully handle signals from Docker or terminal

Start Xvfb wrapper in background and wait for the process to complete.
Because wait exits immediately when a signal for which a trap has been
set, and the signal handler is executed directly after that, we need to
wait again for the background processes to actually finish before exiting.

The signal handler catches INT and TERM and forwards them to the node
process.

The return value from the first wait is stored and sent as exit value.
This commit is contained in:
Joakim Fors 2020-12-04 20:57:06 +01:00
parent 8d2ddd8f95
commit 6b3f557b1f

View file

@ -2,10 +2,22 @@
set -e set -e
handle() {
SIGNAL=$(( $? - 128 ))
echo "Caught signal ${SIGNAL}, stopping gracefully"
kill -s ${SIGNAL} $(pidof node) 2>/dev/null
}
trap handle INT TERM
if ! which -- "${1}"; then if ! which -- "${1}"; then
# first arg is not an executable # first arg is not an executable
xvfb-run -a --server-args="-screen 0 1024x768x24" -- node /app/ "$@" xvfb-run -a --server-args="-screen 0 1024x768x24" -- node /app/ "$@" &
exit $? # Wait exits immediately on signals which have traps set. Store return value and wait
# again for all jobs to actually complete before continuing.
wait $! || RETVAL=$?
wait
exit ${RETVAL}
fi fi
exec "$@" exec "$@"