Created
February 22, 2018 23:36
-
-
Save wware/8a69f8fb8001147dd3e8f7370f35ad00 to your computer and use it in GitHub Desktop.
I want to run a couple Bash processes in parallel in the background. If I use "wait", I might end up waiting for a long-running process to finish after another process has already failed, and in this case I want to stop as soon as I see the failure.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
wait_all() { | |
# As soon as one of the background processes creates the EPIC_FAIL file, | |
# kill all background processes, rm EPIC_FAIL, and stop looping. | |
while [ $(jobs | grep -v Done | wc -l) -ne 0 ]; do | |
sleep 1 | |
if [ -f EPIC_FAIL ]; then | |
rm -f EPIC_FAIL | |
echo OUCH | |
for job in `jobs -p`; do | |
kill -9 $job | |
done | |
break | |
fi | |
done | |
} | |
# If your process fails, it should 'touch EPIC_FAIL' | |
(sleep 2; touch EPIC_FAIL) & | |
# (sleep 2; echo nope) & | |
(sleep 5; echo NOPE) & | |
wait_all |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment