title: How does Linux determine the next PID?
body: <p>How does Linux determine the next PID it will use for a process?  The purpose of this question is to better understand the Linux kernel.  Don't be afraid to post kernel source code.  If PIDs are allocated sequentially how does Linux fill in the gaps?  What happens when it hits the end?</p>
  
  <p>For example if I run a PHP script from Apache that does a <code>&lt;?php print(getmypid());?&gt;</code> the same PID will be printed out for a few minutes while hit refresh.  This period of time is a function of how many requests apache is receiving. Even if there is only one client the PID will eventually change. </p>
  
  <p>When the PID changes, it will be a close number,  but how close? The number does not appear to be entirely sequential. If I do a <code>ps aux | grep apache</code> I get a fair number of processes:</p>
  
  <p><img src="https://i.stack.imgur.com/XYU90.png" alt="enter image description here"></p>
  
  <p>How does Linux choose this next number?  The previous few PID's are still running, as well as the most recent PID that was printed.   How does apache choose to reuse these PIDs? </p>