2

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:

Attempt 1

Using bash 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"

Attempt 2

The same as above, but instead just say wait without specifying pid. Does the same behavior.

...
pid2="$!"
wait

Attempt 3

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?

  • 3
    On Bash v4 (or greater) just one wait -n is all you need. On Bash v3 you might do it by playing with signals. – LL3 Jul 11 at 17:30
  • did you mean to use $! for all of your variable assignments? And the 2nd pid1= should maybe be pid2=? – Jeff Schaller Jul 11 at 17:47
  • @LL3, mind adding an answer? – Ahmet Alp Balkan Jul 12 at 1:14
  • @Jeff, yep sorry just a mistake on the question, edited. – Ahmet Alp Balkan Jul 12 at 1:15
1
wait -n

From help wait in bash:

If the -n option is supplied, waits for the next job to terminate and returns its exit status.

Using wait -n will wait for the next job to terminate. This means that if either of your two background jobs terminates, the call to wait -n will return. You will get the exit status of that job as the exit status of wait -n, but you won't know which one of the jobs terminated.

The -n option for wait was added in bash-4.3-alpha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.