I have a Bash script, which looks similar to this:
#!/bin/bash
echo "Doing some initial work....";
/bin/start/main/server --nodaemon
Now if the bash shell running the script receives a SIGTERM signal, it should also send a SIGTERM to the running server (which blocks, so no trap possible). Is that possible?
Best Answer
Try:
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 withwait
andkill
). Callingwait
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), thewait
call will return (exiting with the server's exit code, or with the signal number + 128 in case 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 usingkill
).