Home > Software design >  How can one obtain disk I/O and network utilization information with WinAPI?
How can one obtain disk I/O and network utilization information with WinAPI?

Time:10-22

I need to access read/write and sent/received type of data about disk and network operations of a specified Windows process as Resource Monitor displays it. How can I do it with WinAPI? Can I do it with PDH?

CodePudding user response:

Process disk information can be obtained using PDH. For obtaining network information, you can refer to this question.

Here is a complete example for your reference.

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <locale.h>
#include <Pdh.h>
#include <string>
#include <pdhmsg.h>
#include <tchar.h>

#pragma    comment(lib,"Pdh.lib")

int nCPU;
using std::string;
using namespace std;
   
int GetData()
{
    HQUERY query;
    double dbVal;
    long iVal;
    //PDH_STATUS status = PdhOpenQuery(NULL, NULL, &query);
    PDH_STATUS status = PdhOpenQuery(0, 0, &query);
    if (ERROR_SUCCESS != status)
    {
        MessageBox(NULL, TEXT("failed"), TEXT(""), MB_OK);
        return -1; 
   }

   HCOUNTER cntProcessCPU, cntProcessMemory;
    HCOUNTER cntProcessDiskRead, cntProcessDiskWrite;
    status = PdhAddCounter(query, L"\\Process(YourProcessName)\\% Processor Time", NULL, &cntProcessCPU);
    status = PdhAddCounter(query, L"\\Process(YourProcessName)\\Working Set - Private", NULL, &cntProcessMemory);
    status = PdhAddCounter(query, L"\\Process(YourProcessName)\\IO Read Bytes/sec", NULL, &cntProcessDiskRead);
    status = PdhAddCounter(query, L"\\Process(YourProcessName)\\IO Write Bytes/sec", NULL, &cntProcessDiskWrite);
    printf("111");  

   if (ERROR_SUCCESS != status)
    {
        MessageBox(NULL, TEXT("add failed"), TEXT(""), MB_OK);
        return -1;
    }

   status = PdhCollectQueryData(query);
    Sleep(500);                 
    status = PdhCollectQueryData(query);
    if (ERROR_SUCCESS != status)
    {
        MessageBox(NULL, TEXT("request failed"), TEXT(""), MB_OK);
        return -1;
    }

   PDH_FMT_COUNTERVALUE pdhValue;
    DWORD dwValue;

   status = PdhGetFormattedCounterValue(cntProcessCPU, PDH_FMT_DOUBLE, &dwValue, &pdhValue);
    if (ERROR_SUCCESS != status)
    {
        MessageBox(NULL, TEXT("Get failed"), TEXT(""), MB_OK);
        return -1;
    }
    else
    {
        dbVal = pdhValue.doubleValue;
        printf("Process-CPU:          =%%          ", (int)(dbVal / nCPU   0.5));
    }

   status = PdhGetFormattedCounterValue(cntProcessMemory, PDH_FMT_DOUBLE, &dwValue, &pdhValue);
    if (ERROR_SUCCESS != status)
    {
        MessageBox(NULL, TEXT("Get failed"), TEXT(""), MB_OK);
        return -1;
    }
    else
    {
        dbVal = pdhValue.doubleValue;
        printf("Process-Memory:                
  • Related