-
Notifications
You must be signed in to change notification settings - Fork 1
/
parallel.sh
executable file
·82 lines (70 loc) · 1.72 KB
/
parallel.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#! /bin/bash
## Tries to run commands in parallel. Commands are read from STDIN one
## per line, or from a given file specified by -f.
## Author: Jan Stepanek
file='-'
proc_num=$(grep -c ^processor'\b' /proc/cpuinfo)
prefix=$HOSTNAME-$USER-$$
sleep=10
children=()
names=()
if [[ $1 =~ ^--?h(elp)?$ ]] ; then
cat <<-HELP
Usage: ${0##*/} [-f file] [-n max-processes] [-p tmp-prefix] -s [sleep]
Defaults:
STDIN for file
$proc_num for max-processes (number of processors)
$prefix for tmp-prefix
$sleep for sleep interval
HELP
exit
fi
function debug () {
if ((DEBUG)) ; then
echo "$@" >&2
fi
}
function child_count () {
debug Entering child_count "${children[@]}"
child_count=0
new_children=()
for child in "${children[@]}" ; do
debug Trying $child
if kill -0 $child 2>/dev/null ; then
debug ... exists
let child_count++
new_children+=($child)
fi
done
children=("${new_children[@]}")
echo $child_count
debug Leaving child_count "${children[@]}"
}
while getopts 'f:n:p:s:' arg ; do
case $arg in
f ) file=$OPTARG ;;
n ) proc_num=$((OPTARG)) ;;
p ) prefix=$OPTARG;;
s ) sleep=$OPTARG;;
* ) echo "Warning: unknown option $arg" >&2 ;;
esac
done
i=0
while read -r line ; do
debug Reading $line
name=$prefix.$i
let i++
names+=($name)
while ((`child_count`>=proc_num)) ; do
sleep $sleep
debug Sleeping
done
eval $line 2>$name.e >$name.o &
children+=($!)
debug Running "${children[@]}"
done < <(cat $file)
debug Loop ended
wait
cat "${names[@]/%/.o}"
cat "${names[@]/%/.e}" >&2
rm "${names[@]/%/.o}" "${names[@]/%/.e}"