Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit physical memory per process

I am writing an algorithm to perform some external memory computations, i.e. where your input data does not fit into main memory and you have to consider the I/O complexity.

Since for my tests I do not always want to use real inputs I want to limit the amount of memory available to my process. What I have found is, that I can set the mem kernel parameter to limit the physically used memory of all processes (is that correct?)

Is there a way to do the same, but with a per process limit. I have seen ulimit, but it only limits the virtual memory per process. Any ideas (maybe I can even set it programmatically from within my C++ code)?

like image 677
dcn Avatar asked Jul 30 '11 10:07

dcn


People also ask

How do I limit memory usage in Python?

Limiting CPU and Memory Usagegetrlimit() method. It returns the current soft and hard limit of the resource. Each resource is controlled by a pair of limits: a soft limit and a hard limit. The soft limit is the current limit, and may be lowered or raised by a process over time.

How do I allocate memory to a process in Linux?

Linux provides a variety of APIs for memory allocation. You can allocate small chunks using kmalloc or kmem_cache_alloc families, large virtually contiguous areas using vmalloc and its derivatives, or you can directly request pages from the page allocator with alloc_pages .


2 Answers

You can try with 'cgroups'. To use them type the following commands, as root.

# mkdir /dev/cgroups
# mount -t cgroup -omemory memory /dev/cgroups
# mkdir /dev/cgroups/test
# echo 10000000 > /dev/cgroups/test/memory.limit_in_bytes
# echo 12000000 > /dev/cgroups/test/memory.memsw.limit_in_bytes
# echo <PID> > /dev/cgroups/test/tasks

Where is the PID of the process you want to add to the cgroup. Note that the limit applies to the sum of all the processes assigned to this cgroup.

From this moment on, the processes are limited to 10MB of physical memory and 12MB of pysical+swap.

There are other tunable parameters in that directory, but the exact list will depend on the kernel version you are using.

You can even make hierarchies of limits, just creating subdirectories.

The cgroup is inherited when you fork/exec, so if you add the shell from where your program is launched to a cgroup it will be assigned automatically.

Note that you can mount the cgroups in any directory you want, not just /dev/cgroups.

like image 166
rodrigo Avatar answered Nov 02 '22 07:11

rodrigo


I can't provide a direct answer but pertaining to doing such stuff, I usually write my own memory management system so that I can have full control of the memory area and how much I allocate. This is usually appliacble when you're writing for microcontrollers as well. Hope it helps.

like image 41
Vern Avatar answered Nov 02 '22 06:11

Vern