Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit Memory allocation to a process in Mac-OS X 10.8

I would like to control the maximum memory, a process can use in Mac-OS X 10.8. I feel that setting ulimit -v should achieve the goals but doesn't seem to be the case. I tried following simple commands :

    ulimit -m 512

    java -Xms1024m -Xmx2048m SomeJavaProgram

I was assuming that 2nd command should fail as Java Process will start by keeping 1024MB of memory for itself but it passes peacefully. Inside my Sample program, I try allocating more than 1024MB using following code snippet:

System.out.println("Allocating 1 GB of Memory");
List<byte[]> list = new LinkedList<byte[]>();
list.add(new byte[1073741824]); //1024 MB
System.out.println("Done....");

Both these programs get executed without any issues. How can we control the max memory allocation for a program in Mac-OS X?

like image 778
Narinder Kumar Avatar asked Sep 04 '12 17:09

Narinder Kumar


1 Answers

I'm not sure if you still need the question answered, but here is the answer in case anyone else happens to have the same question.

ulimit -m strictly limits resident memory, and not the amount of memory a process can request from the operating system.

ulimit -v will limit the amount of virtual memory a process can request from the operating system.

for example...

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char* argv[]) {

    int size = 1 << 20;

    void* memory = NULL;

    memory = malloc(size);

    printf("allocated %i bytes...\n", size);

    return 0; 

}


ulimit -m 512
./memory
allocated 1048576 bytes...


ulimit -v 512
./memory
Segmentation fault


If you execute ulimit -a it should provide a summary of all the current limits for child processes.

As mentioned in comments below by @bikram990, the java process may not observe soft limits. To enforce java memory restrictions, you can pass arguments to the process (-Xmx, -Xss, etc...).

Warning!

You can also set hard limits via the ulimit -H command, which cannot be modified by sub-processes. However, those limits also cannot be raised again once lowered, without elevated permissions (root).

like image 152
Jason Avatar answered Feb 05 '23 05:02

Jason