In my c++ program I am going to start other programs. If those programs use over a certain amount of memory, I want my program to kill their processes. How can that be done?
I will probably use execv to start the programs.
Assuming, you're on a POSIX system, you can limit this by calling setrlimit(2)
after fork()
. For example:
if (fork() == 0) {
struct rlimit limits;
limits.rlim_cur = 10000000; // set data segment limit to 10MB
limits.rlim_max = 10000000; // make sure the child can't increase it again
setrlimit(RLIMIT_DATA, &limits);
execv(...);
}
If your child process attempts to allocate more memory than this, it won't be killed automatically, but it will fail to satisfy memory allocation requests. If the child program chooses to abort in this situation, then it will die. If it chooses to continue, the parent won't be notified of this situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With