다음을 통해 공유


프로세스에 대한 모든 모듈 열거

특정 DLL을 로드한 프로세스를 확인하려면 각 프로세스에 대한 모듈을 열거해야 합니다. 다음 샘플 코드는 EnumProcessModules 함수를 사용하여 시스템의 현재 프로세스 모듈을 열거합니다.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

int PrintModules( DWORD processID )
{
    HMODULE hMods[1024];
    HANDLE hProcess;
    DWORD cbNeeded;
    unsigned int i;

    // Print the process identifier.

    printf( "\nProcess ID: %u\n", processID );

    // Get a handle to the process.

    hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                            PROCESS_VM_READ,
                            FALSE, processID );
    if (NULL == hProcess)
        return 1;

   // Get a list of all the modules in this process.

    if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
    {
        for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
        {
            TCHAR szModName[MAX_PATH];

            // Get the full path to the module's file.

            if ( GetModuleFileNameEx( hProcess, hMods[i], szModName,
                                      sizeof(szModName) / sizeof(TCHAR)))
            {
                // Print the module name and handle value.

                _tprintf( TEXT("\t%s (0x%08X)\n"), szModName, hMods[i] );
            }
        }
    }
    
    // Release the handle to the process.

    CloseHandle( hProcess );

    return 0;
}

int main( void )
{

    DWORD aProcesses[1024]; 
    DWORD cbNeeded; 
    DWORD cProcesses;
    unsigned int i;

    // Get the list of process identifiers.

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        return 1;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the names of the modules for each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        PrintModules( aProcesses[i] );
    }

    return 0;
}

기본 함수는 EnumProcesses 함수를 사용하여 프로세스 목록을 가져옵니다. 각 프로세스에 대해 기본 함수는 PrintModules 함수를 호출하여 프로세스 식별자를 전달합니다. PrintModules는 차례로 OpenProcess 함수를 호출하여 프로세스 핸들을 가져옵니다. OpenProcess가 실패하면 출력에 프로세스 식별자만 표시됩니다. 예를 들어 유휴 및 CSRSS 프로세스에 대해 OpenProcess 는 액세스 제한으로 인해 사용자 수준 코드가 열리지 않으므로 실패합니다. 다음으로 PrintModules는 EnumProcessModules 함수를 호출하여 모듈 핸들 함수를 가져옵니다. 마지막으로 PrintModules는 각 모듈에 대해 한 번씩 GetModuleFileNameEx 함수를 호출하여 모듈 이름을 가져옵니다.