From cfead8ca3cf45d3f47b3a1a3f6bdee0995966d62 Mon Sep 17 00:00:00 2001 From: Jocelyn Le Sage Date: Thu, 15 Mar 2018 07:09:06 -0400 Subject: [PATCH] Gracefully terminates Firefox. --- Dockerfile | 4 ++- rootfs/startapp.sh | 6 +++- rootfs/usr/bin/firefox_wrapper | 60 ++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 2 deletions(-) create mode 100755 rootfs/usr/bin/firefox_wrapper diff --git a/Dockerfile b/Dockerfile index e89be1d..77245b6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,7 +28,9 @@ RUN \ add-pkg \ desktop-file-utils \ adwaita-icon-theme \ - ttf-dejavu + ttf-dejavu \ + # The following package is used to send key presses to the X process. + xdotool # Set default settings. RUN \ diff --git a/rootfs/startapp.sh b/rootfs/startapp.sh index e118fdf..aed2730 100755 --- a/rootfs/startapp.sh +++ b/rootfs/startapp.sh @@ -1,4 +1,8 @@ #!/bin/sh + +set -e # Exit immediately if a command exits with a non-zero status. +set -u # Treat unset variables as an error. + export HOME=/config mkdir -p /config/profile -exec /usr/bin/firefox --profile /config/profile --setDefaultBrowser >> /config/log/firefox/output.log 2>> /config/log/firefox/error.log +exec /usr/bin/firefox_wrapper --profile /config/profile --setDefaultBrowser >> /config/log/firefox/output.log 2>> /config/log/firefox/error.log diff --git a/rootfs/usr/bin/firefox_wrapper b/rootfs/usr/bin/firefox_wrapper new file mode 100755 index 0000000..f8d6844 --- /dev/null +++ b/rootfs/usr/bin/firefox_wrapper @@ -0,0 +1,60 @@ +#!/bin/sh + +# +# This small wrapper is used to gracefully terminate Firefox. It prevents +# the application to receive termination signals directly. Instead, the wrapper +# traps signals and send CTRL+q key presses to Firefox. +# + +FF_PID=0 + +# Gracefully terminate Firefox. This function is called when this script +# receives a termination signal (SIGKILL, SIGINT or SIGQUIT). +kill_firefox() { + # Gracefully close Firefox. + echo "Terminating Firefox..." + xdotool key "Escape" + xdotool key "ctrl+q" + + # And wait for its termination. + if [ "$FF_PID" -ne 0 ]; then + wait $FF_PID + exit $? + fi +} +trap 'kill_firefox' TERM INT QUIT + +# This function is called when this script exits. It makes sure that Firefox is +# fully closed by waiting for all its processes to terminate. +exit_wrapper() { + echo "Waiting for Firefox to completely terminate..." + TIMEOUT=10 + while firefox_running && [ "$TIMEOUT" -gt 0 ]; do + TIMEOUT="$(expr "$TIMEOUT" - 1)" + sleep 1 + done + + if [ "$TIMEOUT" -gt 0 ]; then + echo "Firefox terminated." + else + echo "WARNING: Firefox still not terminated." + fi +} +trap 'exit_wrapper' EXIT + +firefox_running() { + ps | grep -v grep | grep -q '/usr/lib/firefox' +} + +# Make sure to terminate any existing instance. +if firefox_running; then + kill_firefox +fi + +# Start Firefox in background. +/usr/bin/firefox "$@" & + +# And wait for its termination. +FF_PID=$! +wait $FF_PID +exit $?