I have a Bash script that starts one web server, does some work, and then starts a second web server. I would like the script to exit, and for both of these servers to be terminated, if either server exits or the user types Ctrl+C.
What I have now looks like this:
start_server_1 &
server_1_pid=$!
trap "kill $server_1_pid" EXIT
# ...do some work that requires server 1 to be running...
start_server_2 || exit $?
This correctly shuts down both servers if the user types Ctrl+C. If Server 1 exits, however, then Server 2 and the script itself continue to run. How can I make sure that both servers and the script will be taken down if one of these processes exits?