I want to get the allocated memory of a process.
Because I want to kill it if it uses too much memory.
I have got the process name and the PID.
I just need the amount of memory allocated and a function to kill the process.
This is code I have:
//-------------------------------------------------
// COMPILE WITH VS: cl /EHsc PrintProcess.cpp
//-------------------------------------------------
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
if (NULL == hProcess ) return;
HMODULE hMod;
DWORD cbNeeded;
if( !EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) ) return;
// Get the process name.
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );
// Print the process name and identifier.
_tprintf( TEXT("%s (PID: %u)\n"), szProcessName, processID );
// Release the handle to the process.
CloseHandle( hProcess );
}
//-------------------------------------------------------------------
void KillProcess(int MemorySize, DWORD processID)
{
if(MemorySize<1024)
{
//How to kill the process here??
}
}
//-------------------------------------------------------------------
int main( void )
{
// Get the list of process identifiers.
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return 1;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
PrintProcessNameAndID( aProcesses[i] );
//How to get the allocated Memory here??
KillProcess(MemorySize, aProcesses[i]);
}
}
system("Pause");
return 0;
}
//-------------------------------------------------------------------
When I have what I need I’m going to make a daemon with this.
I’m going to put it inside a thread and an infinite loop to verify the process continuously.