等待進程結束函數中的BUG

偶然發現一個BUG,有一個函數是這樣寫的:


windows

void WaitProcExit(DWORD dwPid)
{
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, dwPid);
    if ( NULL == hProcess )
    {
        DWORD dwErr = GetLastError();
        Printf("GetLastError=%d.\n", dwErr);
    }
    WaitForSingleObject(hProcess,INFINITE);
    
    //do something after the target process exit
    //....
    
    return;
}

 



這個函數的功能是等待傳入的PID進程退出,而後執行一些業務。
可是在某些環境下執行並不是由預期效果。

經過GetLastError獲得結果爲5,也就是權限問題。
由於dwPid所在的進程爲管理員權限,執行WaitProcExit()函數的進程爲用戶權限,因此OpenProcess失敗了。
則改代碼應該修改成:

函數

void WaitProcExit(DWORD dwPid)
{
    HANDLE hProcess = OpenProcess(SYNCHRONIZE, 0, dwPid);
    if ( NULL == hProcess )
    {
        DWORD dwErr = GetLastError();
        Printf("GetLastError=%d.\n", dwErr);
    }
    WaitForSingleObject(hProcess,INFINITE);
    
    //do something after the target process exit
    //....
    
    return;
}

 



應使用SYNCHRONIZE權限OpenProcess。
SYNCHRONIZE  的描述是:    The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state.

具體能夠參見:https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880%28v=vs.85%29.aspxspa

相關文章
相關標籤/搜索