Reputation: 229
The short version: My bash script has a function.
This function then launches several instances (a maximum of 10) of another function in the background (with &
).
I keep a count of how many are still active with jobs -p | wc -w
in a do loop. When I'm done with the loop, I break
.
I then use wait
to ensure that all those processes terminate before continuing.
However, when I check the count (with jobs -p
) I sometimes find this:
[10] 9311 Done my_background_function_name $param
How can I get wait
to only proceed when all the launched child-processes have completely terminated and the jobs list is empty?
Why are jobs sometimes shown with "Done" and sometimes not?
Clearly, my knowledge of how jobs
works is deficient. :)
Thanks.
Upvotes: 2
Views: 1580
Reputation: 11
Inside a bash script, it seems that when all jobs has ended, jobs -p still returns the last one finished. This works for me in bash:
while true; do
sleep 5
jobs_running=($(jobs -l | grep Running | awk '{print $2}'))
if [ ${#jobs_running[@]} -eq 0 ]; then
break
fi
echo "Jobs running: ${jobs_running[@]}"
done
Using the "wait" command you cannot tell when each process ends. With the previous algorithm you can.
Upvotes: 1