QueryWorkingSet总是返回false

时间:2018-11-03 12:04:40

标签: c++ windows winapi

我试图获取分配给进程的大小,由映像,私有和映射描述。我正在使用QueryWorkingSet获取工作集信息,然后获取工作集块。

当我第一次调用它时,GetLastError方法返回预期的24,因此,下次我调用QueryWorkingSet时,我为块设置了不同的大小,但随后却得到了998的错误代码。

我使用QueryWorkingSet错误还是我获得了具有错误访问权限的进程的句柄,或者我调整大小是不够的?

#include "pch.h"
 #include <Windows.h>
 #include<WinDef.h>
 #include <psapi.h>
 #include <iostream>

typedef struct {
    DWORD img;
    DWORD map;
    DWORD prv;
} CommitCounters, *PCommitCounters;


BOOL  GetCommitCountersFromProcess(_In_ int pid, _Out_ PCommitCounters committedCounter ) {
    int numberOfTries = 3;
    SYSTEM_INFO si;
    GetSystemInfo(&si);
    DWORD pageSz = si.dwPageSize;

    PSAPI_WORKING_SET_INFORMATION wsi, *pwsi;
    pwsi = &wsi;
    DWORD ws_size;
    MEMORY_BASIC_INFORMATION mbi, *pmbi;
    pmbi = &mbi;

    HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
    wsi.NumberOfEntries = 0;

    QueryWorkingSet(processHandle, &wsi, sizeof(pwsi));
    BOOL res = false;
    committedCounter->img = 0;
    committedCounter->map = 0;
    committedCounter->prv = 0;

    while (numberOfTries > 0) {
    DWORD lastError = GetLastError();

        //ERROR_BAD_LENGTH
    if (lastError == 24) {
        ws_size = sizeof(wsi) + sizeof(PSAPI_WORKING_SET_INFORMATION) + sizeof(PSAPI_WORKING_SET_BLOCK) * wsi.NumberOfEntries;
        pwsi = (PSAPI_WORKING_SET_INFORMATION*) malloc(ws_size);

        pwsi->NumberOfEntries = wsi.NumberOfEntries;
        BOOL resQws = QueryWorkingSet(processHandle, &wsi, ws_size);
        DWORD teste = sizeof(wsi);
        if (resQws) {
            for (int i = 0; i < pwsi->NumberOfEntries; i++) {
                PSAPI_WORKING_SET_BLOCK ws_block = pwsi->WorkingSetInfo[1];
                //Access page information.
                SIZE_T size = VirtualQuery((LPCVOID*)ws_block.VirtualPage, &mbi, 1);
                if (size != 0 && pmbi ->State == 0x1000) {
                    switch (pmbi->Type)
                    {
                    case 0x1000000: // MEM_IMAGE
                        committedCounter->img += pageSz;
                        break;
                    case  0x40000: //MEM_MAPPED
                        committedCounter->map += pageSz;
                        break;
                    case 0x20000: //MEM_PRIVATE
                        committedCounter->prv += pageSz;
                        break;
                    }
                }
                else if (size == 0) {
                    return res;
                }
            }
            CloseHandle(processHandle);
            res = true;
            return res;
        }
        free(pwsi); 
    }
        numberOfTries--;
}

    CloseHandle(processHandle);
    return false;

}

1 个答案:

答案 0 :(得分:0)

您的代码中有错字。只需更改:

BOOL resQws = QueryWorkingSet(processHandle, &wsi, ws_size);

收件人:

BOOL resQws = QueryWorkingSet(processHandle, pwsi, ws_size);

然后呼叫成功。

可能还有其他错误,但我没有调查。