进程枚举之PSAPI函数
使用PSAPI (Process StatusAPI)函数
这是一种Windows NT/2000下的方法。核心是使用EnumProcesses函数。它的原型如下:
BOOL EnumProcesses(
__out DWORD *lpidProcess, // 用于保存所有进程的PID的数组
__in DWORD cb, // 上述数组的大小
__out DWORD *cbNeeded // PID数组中实际返回的(有效)字节数
);
当获得系统中所有进程的PID后,我们就可以使用OpenProcess函数打开指定的进程,再调用GetModuleBaseName获得该进程的名字,调用EnumProcessModules枚举该进程调用的所有模块,调用GetModuleFileNameEx获得模块文件的全路径。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "psapi.h"
#pragma comment(lib,"psapi.lib")
void PrintProcessNameAndID( DWORDprocessID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
//Get a handle to the process.
HANDLEhProcess = 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 );
CloseHandle(hProcess );
}
void main( )
{
//Get the list of process identifiers.
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return;
//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++ )
if(aProcesses[i] != 0 )
PrintProcessNameAndID(aProcesses[i] );
system("pause");
}