I am trying to check how many active processes are running in a bash script. The idea is to keep x processes running and when one finished then the next process is started.
For testing purposes I set up this script:
find $HOME/Downloads -name "dummy" &
find $HOME/Downloads -name "dummy" &
find $HOME/Downloads -name "dummy" &
while true
do
pids=()
while read pid; do
echo "PID: $pid"
pids+=("$pid")
done < <(jobs -p)
jobs -p
echo "Active processes: ${#pids[@]}"
if [ ${#pids[@]} -lt 2 ]; then
break
fi
echo "Process(es) still running... ${pids[@]}"
sleep 1
done
But this does not work because jobs -p
continues to return the job ids even when the processes have finished.
The following example shows the problem in detail:
#!/bin/bash
find $HOME/Downloads -name "dummy" &
find $HOME/Downloads -name "dummy" &
find $HOME/Downloads -name "dummy" &
while true
do
jobs -p # continues to print all 3 jobs
sleep 1
done
How can I get the active jobs in the while
loop?
Regards,
wait -n -p var
in a loop to wait for the next job to finish and keep track of which jobs have not yet finished yourself, rather then seeing which jobs have not yet reported their exit status.parallel(1)
is (its basic variant or GNUparallel
). Maybe you're trying to reinvent it.parellel
seems indeed an option but I have already setup all my scripts. The hint from @icarus usingwait -n
was easy to integrate into the existing scripts and works great.parallel
will only run many instances of the same command.