0
trap exit_gracefully TERM

exit_gracefully() {
    echo "start.sh got SIGTERM"
    echo "Sending TERM to child_process_1_pid: ${child_process_1_pid}"
    echo "Sending TERM to child_process_2_pid: ${child_process_2_pid}"
    echo "Sending TERM to child_process_3_pid: ${child_process_3_pid}"
    kill -TERM ${child_process_1_pid} ${child_process_2_pid} ${child_process_3_pid}
}

consul watch -http-addr=${hostIP}:8500 -type=key -key=${consul_kv_key} /child_process_1.sh 2>&1 &
child_process_1_pid=$!

/child_process_2.sh &
child_process_2_pid=$!

/child_process_3.sh &
child_process_3_pid=$!

/healthcheck.sh &

/configure.sh

# sleep 36500d &
# wait $!

wait ${child_process_1_pid} ${child_process_2_pid} ${child_process_3_pid}

echo 'start.sh exiting'

start.sh is the parent script. When SIGTERM is trapped, it is forwarded to 3 of its child processes. If # sleep 36500d & # wait $! is commented (removed from code), start.sh does not wait for child_process_1.sh, child_process_2.sh and child_process_3.sh to receive SIGTERM, handle it and exit before exiting the parent process (start.sh), instead start.sh exits immediately on receiving SIGTERM even before child processes could handle it. But if I keep sleep 36500d & wait $! uncommented in the code, parent process (start.sh) waits for child processes (1, 2, and 3) to receive, handle Sigterm and exit first before exiting itself.

Why does this difference exist even though I wait for 3 pids (of child processes) in either case? Why should I need sleep when I am waiting for 3 pids?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • Check the value returned by wait. Generally, if it is greater than 128, then it was prematurely terminated by a signal (by signal $? - 128), so you perhaps are looking to do something like `while wait $pid1 $pid2 $pid3; test $? -ge 128; do : ; done` – William Pursell Jul 30 '19 at 04:12

1 Answers1

1

Receiving a signal will cause any wait command in progress to return.

This is because the purpose of a signal is to interrupt a process in whatever it's currently doing.

All the effects you see are simply the result of the current wait returning, the handler running, and the script continuing from where the wait exited.

that other guy
  • 116,971
  • 11
  • 170
  • 194