2010-03-05 37 views
2

試圖實現窮人對進程是否仍在運行的測試(基本上等同於簡單的kill(pid, 0)。)WINSDK:確定任意pid是否標識Windows上正在運行的進程

希望能夠簡單地調用OpenProcess並獲得一些最小的所需訪問權限,然後測試GetLastError() == ERROR_INVALID_PARAMETERGetExitCodeProcess(...) != STILL_ACTIVE

很好的嘗試...在Windows XP上運行,作爲管理員:

HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); 
if (!hProc) { 
    DWORD dwLastError = GetLastError(); 
} 

...當pid由不同的(非SYSTEM)用戶擁有時,與dwLastError == ERROR_ACCESS_DENIED失敗。此外,如果pid最初由不同的用戶擁有但後來終止,OpenProcess也失敗了ERROR_ACCESS_DENIED(而不是ERROR_INVALID_PARAMETER。)

我是否必須使用Process32First/Process32NextEnumProcesses

我絕對不想使用SeDebugPrivilege

謝謝, V

+1

另請參閱http://stackoverflow.com/questions/1591342/how-to-determine-if-a-wi ndows-process-is-running可能有其他更可靠的方法 – rogerdpack 2012-09-28 00:17:51

+0

@rogerdpack在這種情況下唯一可用的信息是'pid'。沒有手柄可用。我知道關於http://stackoverflow.com/questions/1591342/how-to-determine-if-a-windows-process-is-running,我甚至在那裏提出了一條評論。 :) – vladr 2012-10-09 18:44:52

+0

是的,更多我正在發表評論以提醒用戶我已經添加了一個可能適用於此問題的答案,但也不希望將其添加到這兩個地方。乾杯! – rogerdpack 2012-10-10 21:29:15

回答

0
static BOOL 
isProcessAlive(DWORD th32ProcessID) { 
    BOOL bSuccess = FALSE; 

    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 
    if (hSnap != INVALID_HANDLE_VALUE) { 
    PROCESSENTRY32 pe32 = { sizeof(pe32), 0 }; 
    if (Process32First(hSnap, &pe32)) { 
     while (pe32.th32ProcessID != pid && Process32Next(hSnap, &pe32)); 
     _ASSERT(GetLastError() == 0 || GetLastError() == ERROR_NO_MORE_FILES); 
     bSuccess = (pe32.th32ProcessID == th32ProcessID); 
    } 
    CloseHandle(hSnap); 
    } 
    return bSuccess; 
} 
1

如果你有一個進程ID:

// this should succeed even when a medium integrity process 
// requests access to a high integrity process 
if (HANDLE h = OpenProcess(SYNCHRONIZE, FALSE, pid)) 
{ 
    // do a wait, if the handle is signaled: not running 
    DWORD wait = WaitForSingleObject(h, 0); 
    if (wait == WAIT_OBJECT_0) return FALSE; 
} 
// cannot get a handle to the process: 
// probably running at system integrity level 
// I'm not sure how reliable this check is, but it seems to work: 
// if access is denied: running 
// if invalid parameter: not running 
else if (GetLastError() != ERROR_ACCESS_DENIED) return FALSE; 

如果你有一個窗口句柄應該只要進程正在運行是有效的,這是一個很好的選擇:

if (hWnd && !IsWindow(hWnd)) return FALSE; 
+0

Windows XP之後是否修復了這個問題? 「如果'pid'最初由不同的用戶擁有,但已經終止,'OpenProcess'也會因'ERROR_ACCESS_DENIED'(而不是'ERROR_INVALID_PARAMETER')失敗。」 – vladr 2015-02-10 00:42:39

相關問題