From 99adad577145497cf343b65647fe4f470d01ec0a Mon Sep 17 00:00:00 2001 From: Alexandre <44178713+alexbelgium@users.noreply.github.com> Date: Thu, 5 Dec 2024 11:34:40 +0100 Subject: [PATCH] Improve PID catching --- .templates/ha_entrypoint.sh | 47 +++++++++++++++---------------------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/.templates/ha_entrypoint.sh b/.templates/ha_entrypoint.sh index 27d74254c..e4195c1f2 100755 --- a/.templates/ha_entrypoint.sh +++ b/.templates/ha_entrypoint.sh @@ -1,40 +1,20 @@ #!/command/with-contenv bashio # shellcheck shell=bash -# Only trap SIGTERM if the script's PID is 1 -if [ "$$" -eq 1 ]; then - set -m - terminate() { - echo "Termination signal received, forwarding to subprocesses..." - - # Gracefully terminate subprocesses - for pid in "${pids[@]}"; do - echo "Terminating PID $pid" - kill -TERM "$pid" 2>/dev/null - done - - # Wait for all child processes to terminate - wait - echo "All subprocesses terminated. Exiting." - exit 0 - } -fi - echo "Starting..." -# Array to hold the PIDs of the subprocesses -pids=() - #################### # Starting scripts # #################### +pids=() +pids+=(1) for SCRIPTS in /etc/cont-init.d/*; do [ -e "$SCRIPTS" ] || continue echo "$SCRIPTS: executing" # Check if run as root - if [ "$(id -u)" == 0 ]; then + if test "$(id -u)" == 0 && test "$(id -u)" == 0; then chown "$(id -u)":"$(id -g)" "$SCRIPTS" chmod a+x "$SCRIPTS" else @@ -60,15 +40,12 @@ for SCRIPTS in /etc/cont-init.d/*; do sed -i "s/bashio::exit.nok/return 1/g" "$SCRIPTS" sed -i "s/bashio::exit.ok/return 0/g" "$SCRIPTS" # shellcheck source=/dev/null - source "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?" & + source "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?" && pids+=($!) else # Support for posix only shell - "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?" & + "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?" && pids+=($!) fi - # Track the PID of the background process - pids+=($!) - # Cleanup rm "$SCRIPTS" done @@ -80,6 +57,20 @@ done if [ "$$" -eq 1 ]; then echo " " echo -e "\033[0;32mEverything started!\033[0m" + terminate() { + echo "Termination signal received, forwarding to subprocesses..." + + # Gracefully terminate subprocesses + for pid in "${pids[@]}"; do + echo "Terminating PID $pid" + kill -TERM "$pid" 2>/dev/null + done + + # Wait for all child processes to terminate + wait + echo "All subprocesses terminated. Exiting." + exit 0 + } trap terminate SIGTERM SIGINT while true; do sleep 86400 & wait $!; done else