gpt4 book ai didi

c++ - windows EnumProcesses 一些进程名称为

转载 作者:行者123 更新时间:2023-11-30 04:51:42 25 4
gpt4 key购买 nike

你好我有this运行示例代码,它使用 x 打印所有当前正在运行的进程的进程名称和 PIDS。不过,其中只有一些显示真实名称,其他显示为(如下面的输出图像所示)

enter image description here

我想知道这是否是预期的行为,并且并非所有进程都有名称(我可以看到这是最小后台进程的情况),或者我是否错误地使用了 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

访问 64 位进程

如果您只想要一个正在运行的进程列表,请使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com