Does Windows 7 recycle process id (PID) numbers?

DraxDomax picture DraxDomax · Oct 10, 2014 · Viewed 9.8k times · Source

I have this little test program that tracks PID's as they are created and shut down. I am investigating a problem that my program has found and would like to ask you about this in order to have a better idea on what's going on.

When a windows process is started, it gets a PID but when the process is shut down, does the PID become retired (like a star basketballer's jersey number) or is it possible for a new, entirely unrelated, process to be created under that released PID?

Thanks

Answer

David Heffernan picture David Heffernan · Oct 10, 2014

Yes, process IDs may be recycled by the system. They become available for this as soon as the last handle to the process has been closed.

Raymond Chen discussed this matter here: When does a process ID become available for reuse?

The process ID is a value associated with the process object, and as long as the process object is still around, so too will its process ID. The process object remains as long as the process is still running (the process implicitly retains a reference to itself) or as long as somebody still has a handle to the process object.

If you think about it, this makes sense, because as long as there is still a handle to the process, somebody can call WaitForSingleObject to wait for the process to exit, or they can call GetExitCodeProcess to retrieve the exit code, and that exit code has to be stored somewhere for later retrieval.

When all handles are closed, then the kernel knows that nobody is going to ask whether the process is still running or what its exit code is (because you need a handle to ask those questions). At which point the process object can be destroyed, which in turn destroys the process ID.