Skip to content

Instantly share code, notes, and snippets.

@specialunderwear
Created March 2, 2012 12:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save specialunderwear/1958044 to your computer and use it in GitHub Desktop.
Save specialunderwear/1958044 to your computer and use it in GitHub Desktop.
Spawn many processes and wait for all of them to complete
#! /bin/bash
FAIL=0
VERBOSE=0
SLEEP="0"
# parse options
while getopts "vw:d" opt; do
case $opt in
v)
VERBOSE=1
;;
w)
SLEEP=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
# remove option from args
shift $(($OPTIND - 1))
# warn if not enough args
if [ $# -lt 2 ]; then
echo "Usage: many [-v] [-w seconds] number_of_processes command [args]"
exit
fi
NUM_PROCS=$1
shift 1
echo "Spwaning $NUM_PROCS processes, waiting $SLEEP seconds in between spawns."
T="$(date +%s)"
for (( i = 0; i < $NUM_PROCS ; i++ ))
do
if [ $VERBOSE != "0" ]; then
$@ &
PIDLIST="$PIDLIST $!"
sleep $SLEEP
else
$@ > /dev/null &
PIDLIST="$PIDLIST $!"
trap "kill $PIDLIST" SIGINT SIGTERM
sleep $SLEEP
fi
done
echo -en "\033[1;31mDone spawning $NUM_PROCS processes in $(($(date +%s)-T)) seconds\033[0m \n"
echo "Waiting for completion now ..."
WAIT=0
for job in $PIDLIST
do
let WAIT+=1
wait $job || let "FAIL+=1"
done
if [ "$FAIL" == "0" ];
then
echo "All processes completed succesfully."
else
echo "($FAIL) processes exited with an error!"
fi
T="$(($(date +%s)-T))"
echo "Time in seconds: ${T}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment