WINSDK: determining if an arbitrary pid determines the current process in Windows

Attempting to introduce a poor performance test or not (essentially equivalent to the trivial kill(pid, 0) .)

Hoped to be able to just call OpenProcess with the minimum desired access, then check either GetLastError() == ERROR_INVALID_PARAMETER or GetExitCodeProcess(...) != STILL_ACTIVE .

Good try ... Running on Windows XP with administrator privileges:

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

... fails with dwLastError == ERROR_ACCESS_DENIED when the pid belongs to another user (not SYSTEM). Moreover, if the pid originally belonged to another user, but has since been completed, OpenProcess also fails with ERROR_ACCESS_DENIED (not ERROR_INVALID_PARAMETER .)

Do I need to use Process32First / Process32Next or EnumProcesses ?

I absolutely do not want to use SeDebugPrivilege .

Thank you in

+2
security windows process winapi
Mar 05
source share
2 answers
 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; } 
0
Mar 12 '10 at 6:30
source share

If you have a process 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 you have a window handle that must be valid as long as the process is running, this is a good alternative:

 if (hWnd && !IsWindow(hWnd)) return FALSE; 
+1
Jan 31 '15 at 22:41
source share



All Articles