Narinder Kumar
Narinder Kumar

Reputation: 481

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?

Upvotes: 13

Views: 10724

Answers (2)

tmillr
tmillr

Reputation: 133

Currently, on macOS Sonoma 14.2.1, the manpage for ulimit (e.g. man 3 ulimit) says the following:

The ulimit() function will get and set process limits.  Currently, this is limited to the maximum file size.

The is from the ulimit(3) manual/manpage that comes bundled with macOS and it is dated January 4, 2003.

As for the ulimit builtin shell command, it is likely that all this is is a wrapper around the ulimit() C function. Therefore, it does not appear to be possible to set memory limits with ulimit on macOS. Perhaps try using the setrlimit() C function instead.

The only other thing I'm aware of is that it is possible to set/specify process limits for agents and daemons (see man launchd.plist).

Upvotes: 2

Jason
Jason

Reputation: 3917

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).

Upvotes: 11

Related Questions