node ninja
node ninja

Reputation: 32986

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

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.

Upvotes: 5

Views: 2530

Answers (3)

Mike DeSimone
Mike DeSimone

Reputation: 42805

Read up on the setrlimit function. You probably want something like:

#include <sys/resource.h>

struct rlimit limits;
limits.rlim_cur = // soft limit
limits.rlim_max = // hard limit
int err = setrlimit(RLIMIT_DATA, &limits);
if(err) ...

This assumes you're writing for Unix/Linux/BSD/Mac/etc., not Windows... which seems like a good guess since you're using execv.

A couple notes: the soft limit (rlim_cur) may notify the process that the limit is exceeded. Exceeding the hard limit (rlim_max) makes malloc() fail, setting errno to ENOMEM, which usually leads to the process dying. Read the man page or try it out to see how it works on your system. If the stack outgrows rlim_max, you may get a SIGSEGV signal.

Generally, only a root process can raise rlim_max. A regular process can lower rlim_max or set rlim_cur to anything in the range between 0 and rlim_max.

Upvotes: 5

Greg Hewgill
Greg Hewgill

Reputation: 992955

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.

Upvotes: 8

Robᵩ
Robᵩ

Reputation: 168616

In Linux, you probably want to use setrlimit. Don't bother killing the children, though. When they run out of memory, they'll die on their own.

Upvotes: 4

Related Questions