Can OpenProcess with error code ERROR_ACCESS_DENIED be used to know if process exists?

五迷三道 提交于 2020-01-25 17:46:07

问题


I run the following code on a Windows platform. The purpose is the know if a specific process ID refers to an existing process.

BOOL bProcessExists = FALSE;
HANDLE hProcHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcID);
if(hProcHandle)
{
    bProcessExists = TRUE;
    ::CloseHandle(hProcHandle);
}
else
{
    if(::GetLastError() == ERROR_ACCESS_DENIED)
    {
        bProcessExists = TRUE;
    }
}

The process that runs the code above does not run elevated and I found out that OpenProcess can return access denied for some process IDs.

Will the code above be valid?


回答1:


I'd be more worried about your assumption that being able to open the process means the process exists (except for extremely loose definitions of "exists").

An entry for the process will be retained as long as there's at least one handle to that process open. If (for example) a parent spawns a process, then keeps a handle to the child process, there will still be an entry for the child process, even after that process has exited. In that situation, assuming you have the proper rights, you'll be able to open a handle to the process, even though the process has already exited.

To handle this case correctly, you probably want to call GetExitCodeProcess, and only say the process exists if that returns STILL_ALIVE as the process' status.

As for the other part, I can't say with certainty that it'll work, but I'd say there's a good chance. I've used a similar technique for verifying users' passwords -- have them enter a proposed user-name and password. Then use NetUserChangePassword (with out the right to change the password). Then you look at the error you get -- ERROR_ACCESS_DENIED means the user-name/password combo they entered was valid, and ERROR_INVALID_PASSWORD means it wasn't valid.



来源:https://stackoverflow.com/questions/11279035/can-openprocess-with-error-code-error-access-denied-be-used-to-know-if-process-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!