WINSDK:确定一个任意的pid是否标识Windows上正在运行的进程

试图执行一个穷人的testing过程是否仍在运行(本质上相当于微不足道的kill(pid, 0)

希望能够简单地调用OpenProcess一些最小的期望访问,然后testingGetLastError() == ERROR_INVALID_PARAMETERGetExitCodeProcess(...) != STILL_ACTIVE

不错的尝试…在Windows XP上以pipe理员身份运行:

 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

Solutions Collecting From Web of "WINSDK:确定一个任意的pid是否标识Windows上正在运行的进程"

如果你有一个进程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; 
 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; }