简体   繁体   中英

Get process memory information

I've been trying to get process memory information in windows, and I've been following Microsoft docs and I've got this code but it doesn't seem to work. It is supposed to print succeeded, but it doesn't print anything at all. My debugging tells me its because hProcess = null, but i don't understand why. Here is my current code

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

using namespace std;

int main()
{
    DWORD aProcesses[1024], cbNeeded, cProcesses;

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

    cProcesses = cbNeeded / sizeof(DWORD);

    for (int i = 0; i < cProcesses; i++ )
    {
    int processID = aProcesses[i];
    HANDLE hProcess;
    PROCESS_MEMORY_COUNTERS pmc;
    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );

    if (NULL == hProcess)
        return 2;

    if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )
    {
        cout<<"SUCCEEDED";
    }

    CloseHandle( hProcess );
    }

    return 0;
}

You probably don't have permission to read memory of certain (privileged system) processes. Check GetLastError if you get a NULL handle back from OpenProcess .

In general checking and handling Win32 error conditions is a good practice, even if the API 'usually' works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM