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.
-
1Which language are you using? C or C++? – Dec 11 '13 at 18:48
-
4What operating system? – Brian Dec 11 '13 at 18:48
-
Yes you can but how you do it will vary depending on the OS – Pepe Dec 11 '13 at 18:50
-
Also, do you want to write a detector in c++? Or would a shell script suffice. – Brian Dec 11 '13 at 18:50
-
Well i'm learning both so an answer in either one is fine.I'm using windows 7 x64 – Hunterfang Dec 11 '13 at 18:51
3 Answers
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.

- 277,958
- 43
- 419
- 720
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

- 1
- 1

- 1,062
- 1
- 9
- 27
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).

- 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