你好,我有 this示例代码正在运行,它使用 x 打印所有当前正在运行的进程的进程名称和 PIDS。但只有其中一些显示实际名称,其他显示为(如下面的输出图像所示)
我想知道这是否是预期的行为,并且并非所有进程都有名称(我可以看到最小后台进程就是这种情况),或者我是否错误地使用了 EnumProcesses 函数。
我的代码是:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>
#include <tlhelp32.h>
#include <tchar.h>
//https://learn.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-processes
void PrintProcessNameAndID( DWORD processID ){
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );
// Get the process name.
if (NULL != hProcess ){
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ){
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Print the process name and identifier.
_tprintf( TEXT("%s (PID: %u)\n"), szProcessName, processID );
// Release the handle to the process.
CloseHandle( hProcess );
}
//https://learn.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-processes
int main( void ){
// Get the list of process identifiers.
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){
return 1;
}
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
//for ( i = 0; i < cProcesses; i++ ){
for ( i = 0; i < 3; i++ ){
if( aProcesses[i] != 0 ) {
_tprintf( TEXT("aProcesses[%u] = %u (process ID)\n"), i, aProcesses[i] );
PrintProcessNameAndID( aProcesses[i] );
ListProcessThreads( aProcesses[i] );
}
}
return 0;
}
最佳答案
如 documentation 中所述,OpenProcess
对于空闲和 CSRSS 进程失败。
If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last error code is
ERROR_ACCESS_DENIED
because their access restrictions prevent user-level code from opening them.
您必须启用SeDebugPrivilege
(并以管理员权限运行您的应用程序)。此外,如果您的应用程序编译为 32 位,则无法使用 OpenProcess
如果您只需要正在运行的进程的列表,请使用 CreateToolhelp32Snapshot
列出正在运行的进程。
#define UNICODE
#include <Windows.h>
#include <stdio.h>
#include <psapi.h>
#include <tlhelp32.h>
int main()
{
wprintf(L"Start:\n");
HANDLE hndl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPMODULE, 0);
if(hndl)
{
PROCESSENTRY32 process = { sizeof(PROCESSENTRY32) };
Process32First(hndl, &process);
do
{
wprintf(L"%8u, %s\n", process.th32ProcessID, process.szExeFile);
} while(Process32Next(hndl, &process));
CloseHandle(hndl);
}
}
旁注,建议将程序编译为 Unicode。避免使用 _txxx
宏,例如 _tprintf
等。
关于c++ - windows EnumProcesses 某些进程名称为 <unknown>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729026/