Home > Back-end >  How can one know if a process in Windows has exited or not?
How can one know if a process in Windows has exited or not?

Time:10-09

I have an open process handle and PID of the process. Can I use this information to get status of the process if it has exited or not?

CodePudding user response:

The process ID is fairly useless. It's the kind of crutch you'd be forced to use when targeting POSIX, for example.

It's the process handle that is valuable. You can either wait on the process handle using WaitForSingleObject, for example, or ask for the process' exit code with a call to GetExitCodeProcess.

Either API call is capable of reporting whether the process has terminated or not. Assuming that hProcess is the process handle, the following two snippets produce a value that indicates whether the process has terminated:

bool terminated = ::WaitForSingleObject(hProcess, 0) == WAIT_OBJECT_0;
DWORD exit_code{};
bool terminated = ::GetExitCodeProcess(hProcess, &exit_code) &&
                  (exit_code != STILL_ACTIVE);

Note that the first option is more robust. The second option cannot distinguish between a process that's still running, and a process that has terminated but set the exit code to a value of STILL_ACTIVE (259).

  • Related