void PrintMemCpuInfo()
{
printf("是否显示每个进程内存和cpu信息(Y/N):");
int cChar = getch();
if( cChar != 'Y' && cChar != 'y' ) return ;
printf("\n%-30s%-30s%-30s\n","进程","mem-useage","cpu-useage");
/*PERFORMANCE_INFORMATION pif;
memset(&pif,0,sizeof(pif));
if( GetPerformanceInfo(&pif,sizeof(pif)) == FALSE)
{
printf("error-GetPerformanceInfo:%d\n",GetLastError());
return;
}*/
SYSTEM_INFO si;
GetSystemInfo(&si);
OSVERSIONINFO osvi;//定义OSVERSIONINFO数据结构对象
memset(&osvi, 0, sizeof(OSVERSIONINFO));//开空间
osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);//定义大小
GetVersionEx (&osvi);//获得版本信息
//typedef BOOL (WINAPI * JKQueryWorkingSet)(HANDLE,PVOID,DWORD);
//JKQueryWorkingSet jkQueryWorkSet = NULL;
//if (osvi.dwMajorVersion>=6) //vista above
//{
//
HMODULE hK32 = LoadLibraryA("Psapi.dll");
//
jkQueryWorkSet = (JKQueryWorkingSet)GetProcAddress(hK32,"QueryWorkingSet");
//}
//else
//{
//
HMODULE hPsapi = LoadLibraryA("Psapi.dll");
//
jkQueryWorkSet = (JKQueryWorkingSet)GetProcAddress(hPsapi,"QueryWorkingSet");
//}
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if (hSnap)
{
PROCESSENTRY32 entry={sizeof entry};
for (BOOL bState = Process32First(hSnap,&entry);bState;bState=Process32Next(hSnap,&entry))
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,entry.th32ProcessID);
if (hProcess)
{
DWORD dwMemProcess = 0;
//-------------------------------------------------------------------------------
if (osvi.dwMajorVersion<6)
{
PROCESS_MEMORY_COUNTERS_EX procCnt;
if( GetProcessMemoryInfo(hProcess,(PPROCESS_MEMORY_COUNTERS)&procCnt,sizeof(procCnt)) )
{
dwMemProcess = procCnt.WorkingSetSize*1.0f/1024;
if(dwMemProcess==0) dwMemProcess = 1;
_tprintf("%-30s%u KB\n",entry.szExeFile,dwMemProcess);
}
}
else
{
//-------------------------------------------------------------------------------
PSAPI_WORKING_SET_INFORMATION workSet;
memset(&workSet,0,sizeof(workSet));
BOOL bOk = QueryWorkingSet(hProcess,&workSet,sizeof(workSet));
if(bOk || ( !bOk && GetLastError() == ERROR_BAD_LENGTH) )
{
int nSize = sizeof(workSet.NumberOfEntries) + workSet.NumberOfEntries*sizeof(workSet.WorkingSetInfo);
char* pBuf = new char[nSize];
if (pBuf)
{
QueryWorkingSet(hProcess,pBuf,nSize);
PSAPI_WORKING_SET_BLOCK* pFirst = (PSAPI_WORKING_SET_BLOCK*)(pBuf+sizeof(workSet.NumberOfEntries));
DWORD dwMem = 0;
for (ULONG_PTR nMemEntryCnt = 0;nMemEntryCnt<workSet.NumberOfEntries;nMemEntryCnt++,pFirst++)
{
if(pFirst->Shared==0) dwMem += si.dwPageSize;
}
delete pBuf;
if(workSet.NumberOfEntries>0)
{
dwMemProcess = dwMem/1024;
_tprintf("%-30s%u KB\n", entry.szExeFile,dwMemProcess);
}
}
}
else
{
printf("error-QueryWorkingSet:%d\n",GetLastError());
}
}
CloseHandle(hProcess);
}
else
{
_tprintf(TEXT("error-process:%s打开失败\n"),entry.szExeFile);
}
}
CloseHandle(hSnap);
}
}
//添加以下头文件
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>
#pragma comment(lib,"Psapi.lib")