Skip to content
Advertisement

How can I control the number of running processes?

I’m doing a shell script and the unknown situation occurred. I must execute a certain number of processes, lets suppose 12. But I want to limit the executions by ‘t’ each time. So if ‘t’ is 3 I would have to execute 3 processes then 3, 3 and finally 3. But I would like to do it automatically, so I need to monitore those running processes and when one of them has finished I must execute one of the remaining processes.

After some research, I have found the following command:

launch backgroundprocess &
PROC_ID=$!
while kill -0 "$PROC_ID" >/dev/null 2>&1; do
    echo "PROCESS IS RUNNING"
done
echo "PROCESS TERMINATED"

Proposed by cuonglm.

This can help to know if a process is running or not. I tried to create 12 processes and save them in 3 different variables, but it isn’t working properly.

processors=3
counter=0

for A in {1..12}
do
    counter=$((counter+1))
    backgroundprocess &
    PID[$A]=$!

    while [ $counter -eq $processors ]
    do
        if kill -0 "$PID[1]" >/dev/null 2>&1;
        then
            counter=$(($counter-1))
            break
        fi
    done
done

Do any of you know how can I do this work?

Advertisement

Answer

That’s the improvement of your script.

ps -o pid= -p ${PID[$i]} returns PID if process exists.

num stands for the number of job finished.

processors=3
counter=0
num=0

for A in {1..12}
do
    counter=$((counter+1))
    sleep 4 &
    if [ $num -eq 0 ]
    then
        PID[$A]=$!
    else
        PID[$num]=$!
    fi
    echo "$A starts"
    echo $counter

    while [ $counter -eq $processors ]
    do
        for i in `seq 1 $processors`
        do
            if [ ! `ps -o pid= -p ${PID[$i]}` ]
            then
                counter=$(($counter-1))
                echo "$i stopped"
                num=$i
                break
            fi
        done
    done
done
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement