8

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.

xav
  • 5,452
  • 7
  • 48
  • 57
  • 1
    To add you some comparison work - you might want to compare `GetExitCodeProcess` against `WaitForSingleObject` as for determining process completion status. – Roman R. Oct 15 '12 at 17:15

3 Answers3

12

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).

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
  • 3
    I'd also add the process ID *theoretically* may be reused. So that it's generally not a good idea each time to open the process by its ID. Better open its handle once (or save it if you created it, or obtained from some 3rd party). – valdo Aug 13 '17 at 15:13
1

An implementation of IsProcessRunning can also use the GetExitCodeProcess Win32 API.

munsingh
  • 317
  • 2
  • 9
-1

WaitForSingleObject will wait till the process completes/exits. Only then will it return.

user93353
  • 13,733
  • 8
  • 60
  • 122
  • 1
    The zero timeout is part of the ingeniosity (hopefully I spelled that right), it will either time out immediately ( = process running) or fail ( = zombie process). – Damon Oct 15 '12 at 16:57