Set a limit on a process’s size
At times it’s require to limit a process’s memory size by some value. In such cases “ulimit -m” is our best friend. But what if the task to limit not only a certain but all processes on the given system. I didn’t know how to do that, and frankly speaking have never faced with such problem, until recently. To my surprise it was just a matter of reading Linux’s documentation of its VM tunables to find a proper solution. So if swap is disabled then doing the following would tell the kernel not to hand out more than 70 percent of available RAM.
# sysctl -w vm.overcommit_memory=2 # sysctl -w vm.overcommit_ration=70
Conversely, if you do have swap enabled the same statement would limit the maximum possible memory that could be assigned to the processes to a slightly different value. That’s is because the general equation for this is:
commit = swap space(s) size + overcommit_ratio percent * RAM size.
In the end, allow me to cite the official Linux’s documentation:
The Linux kernel supports the following overcommit handling modes
0 – Heuristic overcommit handling. Obvious overcommits of
address space are refused. Used for a typical system. It
ensures a seriously wild allocation fails while allowing
overcommit to reduce swap usage. root is allowed to
allocate slighly more memory in this mode. This is the
default.1 – Always overcommit. Appropriate for some scientific
applications.2 – Don’t overcommit. The total address space commit
for the system is not permitted to exceed swap + a
configurable percentage (default is 50) of physical RAM.
Depending on the percentage you use, in most situations
this means a process will not be killed while accessing
pages but will receive errors on memory allocation as
appropriate.The overcommit policy is set via the sysctl `vm.overcommit_memory’.
The overcommit percentage is set via `vm.overcommit_ratio’.
The current overcommit limit and amount committed are viewable in
/proc/meminfo as CommitLimit and Committed_AS respectively.