问题
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.
回答1:
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
回答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.
回答3:
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).
来源:https://stackoverflow.com/questions/20527472/how-to-detect-a-process-cpu-memory-usage-and-kill-it-when-it-exceeds-a-certain-v