Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the amount of memory a spawned program can use in C++

Tags:

c++

process

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.

like image 429
node ninja Avatar asked Dec 03 '22 08:12

node ninja


1 Answers

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.

like image 185
Greg Hewgill Avatar answered May 20 '23 05:05

Greg Hewgill