Search code examples
c++winapipid

Benefit of Using WaitForSingleObject When Checking Process ID


What is the benefit of using WaitForSingleObject here as opposed to not using it? The first block of code is from a previous answer. The second block is how I am doing it.

BOOL IsProcessRunning(DWORD pid)
{
    HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);
    DWORD ret = WaitForSingleObject(process, 0);
    CloseHandle(process);
    return (ret == WAIT_TIMEOUT);
}

vs

BOOL IsProcessRunning(DWORD pid)
{
   HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
   const bool exists = (process != NULL);
   CloseHandle(process);
   return exists;
}

It seems like using SYNCHRONIZE requires higher privileges and I only want to check the PID for the current user.


Solution

  • When a process completes, it stops running but it doesn't go out of existence until the last handle to it is closed. The first solution distinguishes between those two states (still running or done running). Of course, the answer could be obsolete by the time it has returned.

    If you don't need that distinction, then your approach is fine (though I would name the function something like DoesProcessExist).