您好我运行的this示例代码使用x来打印所有当前正在运行的进程的processNames和PIDS。其中只有一些显示实际名称,其他显示为(如下面的输出图片中所示)
我想知道这是否是预期的行为,并且并非所有进程都有一个名称(我可以看到这是最小化后台进程的情况),或者我是否错误地使用了EnumProcesses函数。
我的代码是:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>
#include <tlhelp32.h>
#include <tchar.h>
//https://docs.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://docs.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流程。
如果指定的进程是空闲进程或其中一个CSRSS进程,则此函数将失败,最后一个错误代码为
ERROR_ACCESS_DENIED
,因为它们的访问限制会阻止用户级代码打开它们。
您必须启用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
宏。