How can I control the number of running processes?

Viewed 224

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?

3 Answers
Related