mirror of
https://github.com/alexbelgium/hassio-addons.git
synced 2026-01-11 02:11:01 +01:00
Improve PID catching
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user