I have a concern whereby in a script, I will be calling parallel versions of a function to run in the background and then issuing a wait.

a () {
  sleep $1

a 10 &
PIDs="$PIDs $!"
a 50000 &
PIDs="$PIDs $!"

wait $PIDs   

The concern is the first function call takes 10 seconds (sleep 10), but the second takes nearly 14 hours (sleep 50000).

I am concerned the PID from the first invocation will be recylced and 14 hours later, when the second invocation is terminates, that PID is being used by another process and will prevent the script from continuing. Or does wait remove the first PID from the list as soon as that invocation completes and just simply waits for the second process to complete rather than waiting for both of them to finish at the end?

2 Answers 2


See for yourself that the wait builtin will not wait for a random process -- only children of the current shell.

sleep 2 &
echo sleeping 3 seconds...
sleep 3
echo waiting for $P ...
wait $P
echo waiting for $R ...
wait $R
echo done

$ ./t.sh
sleeping 3 seconds...
waiting for 93208...     ## this returns immediately, since that PID is gone
waiting for 31941 ...
./t.sh: line 10: wait: pid 31941 is not a child of this shell

I assume that your running Linux. Given that:

You can increase kernel.pid_max in /etc/sysctl.conf. The default value is 32768 and applies if this is not explicitly defined therein. Add something like:

kernel.pid.max = 4000000

Load the modified sysctl.conf with:

# sysctl -p

This can be done without any downtime or other interruption.

  • That shouldn't matter for this use case. See also @JeffSchaller's reply. Commented Jan 13, 2016 at 13:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .