位置:海鸟网 > IT > linux/Unix >

bash控制任务并发数脚本

bash控制任务并发数脚本

使用bash实现控制任务并发数的功能

01
#!/bin/bash
02
#
03

04
CMDS[1]="echo $USER' 01 BEGIN' && sleep 6 && echo $USER' 01 END'"
05
CMDS[2]="echo $USER' 02 BEGIN' && sleep 3 && echo $USER' 02 END'"
06
CMDS[3]="echo $USER' 03 BEGIN' && sleep 7 && echo $USER' 03 END'"
07
CMDS[4]="echo $USER' 04 BEGIN' && sleep 4 && echo $USER' 04 END'"
08
CMDS[5]="echo $USER' 05 BEGIN' && sleep 2 && echo $USER' 05 END'"
09
CMDS[6]="echo $USER' 06 BEGIN' && sleep 5 && echo $USER' 06 END'"
10

11
N=${#CMDS[@]}
12

13
MAX=3
14
PIDS=''
15
for I in $(seq $N)
16
do
17
    while [ 1 -gt 0 ]
18
    do
19
        C=0
20
        pids=''
21
        for PID in $PIDS
22
        do
23
            ps $PID >/dev/null 2>/dev/null
24
            if [ $? -eq 0 ]
25
            then
26
                pids="$pids $PID"
27
                (( C = C + 1 ))
28
            fi
29
        done
30
        PIDS=$pids
31

32
        [ $C -lt $MAX ] && break
33
        sleep 1
34
    done
35

36
    #echo $i ${CMDS[$i]}
37
    CMD=${CMDS[$I]}
38
    bash -c "$CMD" &
39
    PIDS="$PIDS $!"
40
done
41

42
wait