给定一长串输入行(比如一个日志文件),我想启动N个进程并让它们共享并行处理输入的负载。因此,如果N = 3,我只想启动3个进程,以便每个进程接收到其stdin的第三个输入:
process 1: line1, line4, line7...
process 2: line2, line5, line8...
process 3: line3, line6, line9...
我认为xargs -n1 -P3
应该可以实现这一目标,但我想这只是确保不超过3个进程同时运行 #39;有兴趣推出总共不超过3个流程。
答案 0 :(得分:1)
for i in {0..10}; do echo $i; done | { # simulates input
temp_dir=`mktemp -d /tmp/parallel_test.XXX`
N=3
pipes=$(eval echo `echo $temp_dir/{1..$N}`)
mkfifo $pipes
keep_pipes_open=$temp_dir/keep_pipes_open
touch $keep_pipes_open
for pipe in $pipes; do
sed -e "s/^/pipe ${pipe##*/}: /" < $pipe & # sed simulates the proccess you want to run
while [ -f $keep_pipes_open ]; do sleep 1; done > $pipe &
done
typeset -i i=1
while read line; do
echo "$line" > $temp_dir/$i
i=$((i % N + 1 ))
done
rm $keep_pipes_open
wait
rm -rf $temp_dir
}
输出:
pipe 1: 0
pipe 1: 3
pipe 1: 6
pipe 1: 9
pipe 2: 1
pipe 2: 4
pipe 2: 7
pipe 2: 10
pipe 3: 2
pipe 3: 5
pipe 3: 8