From 6b3f557b1f4f2dde31f73e252eb8f1fc011233fb Mon Sep 17 00:00:00 2001 From: Joakim Fors Date: Fri, 4 Dec 2020 20:57:06 +0100 Subject: [PATCH] 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. --- docker-entrypoint.sh | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 097b194..8b7984c 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -2,10 +2,22 @@ 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 # first arg is not an executable - xvfb-run -a --server-args="-screen 0 1024x768x24" -- node /app/ "$@" - exit $? + xvfb-run -a --server-args="-screen 0 1024x768x24" -- node /app/ "$@" & + # 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 exec "$@"