I'm trying to write a bash script that forks two background server processes (whose termination means a problem), and this script would exit as soon as one of them terminates (without waiting for the other one).
Here's what I tried so far:
wait directive. This didn't work because it still waits for both processes to complete. In my case, I'm running two server processes, so if they complete, it means something is wrong, so I should exit this script altogether.
#!/usr/bin/env bash set -e ./server1 & pid1="$!" ./server2 & pid1="$!" wait "$1" wait "$2"
The same as above, but instead just say
wait without specifying pid. Does the same behavior.
... pid2="$!" wait
I tried using sub-shells and exiting from there. But the
exit applies only to the sub-shell, so we still wait for both background processes to finish:
#!/usr/bin/env bash set -e ( ./server1 || echo crash1; exit 1 ) & ( ./server2 || echo crash2; exit 2 ) & wait
Is there way to achieve this (forking two server processes in the background, and exiting as soon as one of them finishes) in bash?