모든 프로세스 열거
다음 샘플 코드는 EnumProcesses 함수를 사용하여 시스템의 각 프로세스 개체에 대한 프로세스 식별자를 검색합니다. 그런 다음 EnumProcessModules 호출되어 각 프로세스 이름을 가져와서 인쇄합니다.
메모
64비트 프로세스의 경우 EnumProcessModulesEx 함수를 사용합니다.
#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;
}
main 함수는 EnumProcesses 함수를 사용하여 프로세스 목록을 가져옵니다. 각 프로세스에 대해 main은 PrintProcessNameAndID 함수를 호출하여 프로세스 식별자를 전달합니다. PrintProcessNameAndIDOpenProcess 함수를 호출하여 프로세스 핸들을 가져옵니다. OpenProcess 실패하면 출력에 프로세스 이름이 <알 수 없는>로 표시됩니다. 예를 들어, 유휴 및 CSRSS 프로세스에 대해 OpenProcess 는 액세스 제한으로 인해 사용자 수준 코드에서 열 수 없으므로 실패합니다. 그런 다음, PrintProcessNameAndIDEnumProcessModules 함수를 호출하여 모듈 핸들을 가져옵니다. 마지막으로 PrintProcessNameAndIDGetModuleBaseName 함수를 호출하여 실행 파일의 이름을 가져오고 프로세스 식별자와 함께 이름을 표시합니다.