用C語言監控一個進程(比如QQ)的內存佔用情況,整合了網上的一些代碼。
頭文件"process_stat.h"
#ifndef PROCESS_STAT_H
#define PROCESS_STAT_H
#ifdef __cplusplus
extern "C" {
#endif
typedef long long int64_t;
typedef unsigned long long uint64_t;
#ifdef __cplusplus
}
#endif
#endif/*PROCESS_STAT_H*/
主函數
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <psapi.h>
#include <assert.h>
#include "process_stat.h"
#include "tlhelp32.h "
UINT GetProcessIdByName(LPCTSTR pszExeFile)
{
UINT nProcessID = 0;
PROCESSENTRY32 pe = {sizeof(PROCESSENTRY32)};
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
if (Process32First(hSnapshot, &pe))
{
while (Process32Next(hSnapshot, &pe))
{
if (lstrcmpi(pszExeFile, pe.szExeFile) == 0)
{
nProcessID = pe.th32ProcessID;
break;
}
}
}
CloseHandle(hSnapshot);
}
return nProcessID;
}
int get_memory_usage(uint64_t* mem, uint64_t* vmem)
{
PROCESS_MEMORY_COUNTERS pmc;
UINT ID = GetProcessIdByName(_T("QQ.exe"));
if(GetProcessMemoryInfo(/*GetCurrentProcess()*/OpenProcess(PROCESS_ALL_ACCESS, FALSE, ID), &pmc, sizeof(pmc)))
{
if(mem) *mem = pmc.WorkingSetSize;
if(vmem) *vmem = pmc.PagefileUsage;
return 0;
}
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{
uint64_t mem, vmem, r, w;
get_memory_usage(&mem, &vmem);
printf("內存使用: %u 字節\n", mem);
printf("虛擬內存使用: %u 字節\n", vmem);
return 0;
}