Menghitung Semua Proses
Kode sampel berikut menggunakan fungsiEnumProcesses untuk mengambil pengidentifikasi proses untuk setiap objek proses dalam sistem. EnumProcessModules kemudian dipanggil untuk mendapatkan setiap nama proses dan mencetaknya.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>
// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1
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 );
}
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++ )
{
if( aProcesses[i] != 0 )
{
PrintProcessNameAndID( aProcesses[i] );
}
}
return 0;
}
Fungsi utama mendapatkan daftar proses dengan menggunakan fungsi EnumProcesses. Untuk setiap proses, fungsi utama memanggil fungsi PrintProcessNameAndID, dengan meneruskan pengidentifikasi proses. PrintProcessNameAndID pada gilirannya memanggil fungsi OpenProcess untuk mendapatkan handle proses. Jika OpenProcess gagal, output menunjukkan nama proses sebagai <tidak diketahui>. Misalnya, OpenProcess gagal untuk proses Idle dan CSRSS karena pembatasan aksesnya mencegah kode tingkat pengguna membukanya. Selanjutnya, PrintProcessNameAndID memanggil fungsiEnumProcessModules untuk mendapatkan handle modul. Terakhir, PrintProcessNameAndID memanggil fungsiGetModuleBaseName untuk mendapatkan nama file yang dapat dieksekusi dan menampilkan nama bersama dengan pengidentifikasi proses.