1

i'm learning c/c++ and i'm wondering if it is possible to detect a process by it's name and kill it when it's cpu/memory usage exceed a certain value. I would apreciate any help with the actual code or just pointing me in the right direction.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
Hunterfang
  • 113
  • 1
  • 6

3 Answers3

2

In recent versions of Windows, you can ask the OS to take care of this for you -- create a Process Job Object and configure limits. The accounting features of the job object will let you track resource usage.

In Linux/Unix you would use ulimit.

Don't try to enforce this yourself. If you have a runaway process, the most likely scenario is that your enforcer won't be scheduled in a timely manner to kill it. You really want help from the kernel, and in particular the thread scheduler.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

For Windows and c++:

Memory Usage

Check out GetProcessMemoryInfo. There's also an example at msdn.

The GetProcessMemoryInfo() function will provide you a pointer to a PROCESS_MEMORY_COUNTERS struct which contains all of the memory usage information.

CPU Usage

For CPU usage it's a little bit more difficult but the following stackoverflow question is related to that: Getting current cpu usage in c++/windows for particular process

Community
  • 1
  • 1
Steve Van Opstal
  • 1,062
  • 1
  • 9
  • 27
0

You need to create a process to monitor your other processes.

To do this in Linux in c++:

You can read from /proc/stat directly, or create a process to run 'ps' and parse its output to find processes with high %cpu. To create a process that runs ps, you'll need to use the 'fork' command.

Then you can call 'execvp' to call 'kill ', a function from .

Same idea goes for the bash script (this is probably quite a bit easier though).

Brian
  • 3,453
  • 2
  • 27
  • 39
  • `ps` is quite functional and makes sense to call. OTOH `kill` is a pretty thin wrapper, might as well just call the `kill` function instead of execing the `kill` binary. – Ben Voigt Dec 11 '13 at 21:22