在 Mac-OS X 10.8 中限制进程的内存分配 [英] Limit Memory allocation to a process in Mac-OS X 10.8
问题描述
我想控制最大内存,一个进程可以在 Mac-OS X 10.8 中使用.我觉得设置 ulimit -v 应该可以实现目标,但似乎并非如此.我尝试了以下简单的命令:
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
我假设第二个命令应该失败,因为 Java 进程将通过为自己保留 1024MB 内存开始,但它会平静地通过.在我的示例程序中,我尝试使用以下代码片段分配超过 1024MB:
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....");
这两个程序都可以毫无问题地执行.我们如何控制 Mac-OS X 中程序的最大内存分配?
Both these programs get executed without any issues. How can we control the max memory allocation for a program in Mac-OS X?
推荐答案
我不确定您是否还需要回答这个问题,但这里是答案,以防其他人碰巧遇到同样的问题.
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
严格限制常驻内存,而不是进程可以从操作系统请求的内存量.
ulimit -m
strictly limits resident memory, and not the amount of memory a process can request from the operating system.
ulimit -v
将限制进程可以从操作系统请求的虚拟内存量.
ulimit -v
will limit the amount of virtual memory a process can request from the operating system.
例如...
#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
如果您执行 ulimit -a
,它应该提供子进程所有当前限制的摘要.
If you execute ulimit -a
it should provide a summary of all the current limits for child processes.
正如@bikram990 在下面的评论中提到的,java 进程可能不会遵守软限制.要强制执行 Java 内存限制,您可以向进程传递参数(-Xmx、-Xss 等...).
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...).
警告!
您还可以通过 ulimit -H
命令设置硬限制,不能被子进程修改.但是,如果没有提升的权限(root),这些限制也不能在降低后再次提高.
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).
这篇关于在 Mac-OS X 10.8 中限制进程的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!