问题描述
试图实现一个进程是否仍在运行的穷人测试(本质上相当于微不足道的kill(pid, 0)
.)
Attempting to implement a poor man's test of whether a process is still running or not (essentially an equivalent of the trivial kill(pid, 0)
.)
希望能够简单地调用 OpenProcess
并具有一些所需的最小访问权限,然后测试 GetLastError() == ERROR_INVALID_PARAMETER
或 GetExitCodeProcess(...)!= STILL_ACTIVE
.
Hoped to be able to simply call OpenProcess
with some minimal desired access then test for either GetLastError() == ERROR_INVALID_PARAMETER
or GetExitCodeProcess(...) != STILL_ACTIVE
.
不错的尝试...在 Windows XP 上以管理员身份运行:
Nice try... Running on Windows XP, as administrator:
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
.)
...fails miserably with dwLastError == ERROR_ACCESS_DENIED
when pid
is owned by a different (not SYSTEM) user. Moreover, if pid
was originally owned by a different user but has since terminated, OpenProcess
also fails with ERROR_ACCESS_DENIED
(not ERROR_INVALID_PARAMETER
.)
我是否必须使用 Process32First
/Process32Next
或 EnumProcesses
?
Do I have to use Process32First
/Process32Next
or EnumProcesses
?
我绝对不想使用SeDebugPrivilege
.
I absolutely do not want to use SeDebugPrivilege
.
谢谢,V
推荐答案
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;
}
这篇关于WINSDK:确定任意 pid 是否标识 Windows 上正在运行的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!