title: Fast way to determine if a PID exists on (Windows)?
body: <p>I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called <a href="http://code.google.com/p/psutil/" rel="nofollow noreferrer"><strong>psutil</strong></a> for reading process information in a cross-platform way. One of the functions is a <code>pid_exists(pid)</code> function for determining if a PID is in the current process list.</p>
  
  <p>Right now I'm doing this the obvious way, using <a href="http://msdn.microsoft.com/en-us/library/ms682629(VS.85).aspx" rel="nofollow noreferrer">EnumProcesses()</a> to pull the process list, then interating through the list and looking for the PID. However, some simple benchmarking shows this is dramatically slower than the pid_exists function on UNIX-based platforms (Linux, OS X, FreeBSD) where we're using <code>kill(pid, 0)</code> with a 0 signal to determine if a PID exists. Additional testing shows it's EnumProcesses that's taking up almost all the time.</p>
  
  <p>Anyone know a faster way than using EnumProcesses to determine if a PID exists? I tried <a href="http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx" rel="nofollow noreferrer">OpenProcess()</a> and checking for an error opening the nonexistent process, but this turned out to be over 4x slower than iterating through the EnumProcesses list, so that's out as well. Any other (better) suggestions?</p>
  
  <p><strong>NOTE</strong>: This is a Python library intended to avoid third-party lib dependencies like pywin32 extensions. I need a solution that is faster than our current code, and that doesn't depend on pywin32 or other modules not present in a standard Python distribution.</p>
  
  <p><strong>EDIT</strong>: To clarify - we're well aware that there are race conditions inherent in reading process iformation. We raise exceptions if the process goes away during the course of data collection or we run into other problems. The pid_exists() function isn't intended to replace proper error handling.</p>
  
  <p><strong>UPDATE</strong>: Apparently my earlier benchmarks were flawed - I wrote some simple test apps in C and EnumProcesses consistently comes out slower and OpenProcess (in conjunction with GetProcessExitCode in case the PID is valid but the process has stopped) is actually much <em>faster</em> not slower.</p>