Last active
January 20, 2022 20:08
-
-
Save npodonnell/f03ce46e8c0f583daf1a48e8f58e490a to your computer and use it in GitHub Desktop.
Run in parallel
This file contains 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
#!/usr/bin/env bash | |
NTOK=3 | |
do_cmd() { | |
echo "Command start $1" | |
sleep 5 | |
echo "Command end $1" | |
return 1 | |
} | |
# Set up 2 pipes: one for the semaphore tokens, and | |
# another one for collecting return values. | |
p=$(mktemp -u) | |
mkfifo $p | |
exec 3<>$p | |
rm $p | |
p=$(mktemp -u) | |
mkfifo $p | |
exec 4<>$p | |
rm $p | |
# Fill the semaphore pipe with tokens | |
for ((i=0; i<$NTOK; i++)); do | |
echo -n "#" >&3 | |
done | |
pids=() | |
# Main execution loop | |
for i in {0..5}; do | |
read -n 1 -u 3 x | |
( | |
do_cmd $i | |
echo "$?" >&4 | |
[[ $i -eq 5 ]] && echo "." >&4 # End | |
echo -n "#" >&3 | |
) & | |
pids+=($!) | |
done | |
for pid in ${pids[@]}; do | |
echo "waiting $pid" | |
wait $pid | |
done | |
#cat <&4 | |
while read e && [[ $e != "." ]]; do | |
echo "exit: $e" | |
done <&4 | |
echo "done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment