5 of 8
Removed misleading/wrong text, explain what actually happens



_term() { 
  printf "%s\n" "Caught SIGTERM signal!" 
  kill -TERM $child 2>/dev/null

trap _term SIGTERM
echo "Doing some initial work...";
/bin/start/main/server --nodaemon &

wait $child

Normally, bash will ignore any signals while a child process is executing. Starting the server with & will background it into the shell's job control system, with $! holding the server's PID (to be used with wait and kill). Calling wait will then wait for the job with the specified PID (the server) to finish, or for any signals to be fired.

When the shell receives SIGTERM (or the server exits independently), the wait call will return (exiting with the server's exit code, or with the signal number + 127 if a signal was received). Afterward, if the shell received SIGTERM, it will call the _term function specified as the SIGTERM trap handler before exiting (in which we do any cleanup and manually propagate the signal to the server process using kill).

  • 137.4k
  • 35
  • 292
  • 373