如何在bash shell中限制同一后台进程的数量?

问题描述

比方说,我有一个循环,其运行次数大致如下:

while *condition*
do
    {
    *cool stuff happens here,including running some programs*
    } &
done

因为它是系统,所以资源很快就会用完,所以我想设置一个限制(例如5或10),然后等待它们完成。我该如何实现?

解决方法

count=0
maxcount=5
for ((i=0;i<10;++i)); do
    { sleep 0.$i; } &
    count=$((count + 1))
    if ((count++ > maxcount)); then
        wait -n
        count=$((count - 1))
    fi
done
# wait for the rest of processes
wait