2011-10-07 70 views
0

我在C++中使用OpenProcess來打開一個進程,但是我在得到它之後無法正確使用它,因爲出現了「無效句柄錯誤」。我知道正確的手柄,因爲當我在這個手柄上執行GetProcessId時,它給了我正確的PID。 這就是我打開這個過程的方式。如何知道進程句柄是否準備就緒

#include <windows.h> 
#include <stdio.h> 
#include <dbghelp.h> 
#pragma (lib, "dbghelp.lib"); 

bool EnablePrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable) 
{ 
    HANDLE hToken; 
    TOKEN_PRIVILEGES tp; 
    LUID luid; 
    bool ret; 

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken)) 
     return FALSE; 

    if (!LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid)) 
     return FALSE; 

    tp.PrivilegeCount   = 1; 
    tp.Privileges[0].Luid  = luid; 
    tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0; 

    ret = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL); 
    CloseHandle(hToken); 

    return ret; 
} 

void main() 
{ 
    EnablePrivilege(SE_DEBUG_NAME, TRUE); 

    STARTUPINFOA startInfo; 
    PROCESS_INFORMATION processInfo; 
    ZeroMemory(&startInfo, sizeof(startInfo)); 
    startInfo.cb = sizeof(startInfo); 
    ZeroMemory(&processInfo, sizeof(processInfo)); 
    DWORD creationFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION; 
    const char* comLine = "Some process path and name"; 

//  Start the child process. 
    if(CreateProcessA(NULL, // No module name (use command line) 
     (LPSTR)comLine, //argv[1],  // Command line 
     NULL,   // Process handle not inheritable 
     NULL,   // Thread handle not inheritable 
     FALSE,   // Set handle inheritance to FALSE 
     creationFlags,    // No creation flags 
     NULL,   // Use parent's environment block 
     NULL,   // Use parent's starting directory 
     &startInfo,   // Pointer to STARTUPINFO structure 
     &processInfo)   // Pointer to PROCESS_INFORMATION structure 
    == false) 
    { 
     printf("FAIL!"); 
return; 
    } 

    SetLastError(0); 
    bool ok = SymInitialize(processInfo.hProcess, NULL, true); 
    int err = GetLastError(); 

} 

由於某種原因,最後的錯誤值是垃圾。
有沒有辦法檢查進程句柄是否可以使用?

+0

你能發佈你的代碼嗎? – crazyjul

+0

您希望看到什麼具體內容? – Idov

+0

如何調用'OpenProcess',你如何處理句柄。 – crazyjul

回答

2

從功能的問題的文檔:

Return value 

If the function succeeds, the return value is an open handle to the specified process. 

這意味着,如果函數成功,你已經獲得一個可用手柄即你要麼與否,沒有地方「你有中間地帶等待「使其可用。在您的特定情況下,您的手柄可能無效,即功能失效。你是否檢查NULL的返回值?你有沒有用GetLastError()看看發生了什麼?

+0

CreateProcess返回true,但也是最後一個錯誤= 2(文件未找到) – Idov

+0

嘗試打印上一個錯誤之前和之後,看看它是否改變。因爲GetLastError可能會從另一個失敗的函數返回值? – LordDoskias

+0

也在你的代碼中,你不使用OpenProcess,而是OpenProcessHandle - 這是失敗的函數嗎? – LordDoskias

相關問題