Linux 什么时候应该将 errno 分配给 ENOMEM?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10966121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should errno be assigned to ENOMEM?
提问by venus.w
The following program is killed by the kernel when the memory is ran out. I would like to know when the global variable should be assigned to "ENOMEM".
以下程序在内存耗尽时被内核杀死。我想知道什么时候应该将全局变量分配给“ENOMEM”。
#define MEGABYTE 1024*1024
#define TRUE 1
int main(int argc, char *argv[]){
void *myblock = NULL;
int count = 0;
while(TRUE)
{
myblock = (void *) malloc(MEGABYTE);
if (!myblock) break;
memset(myblock,1, MEGABYTE);
printf("Currently allocating %d MB\n",++count);
}
exit(0);
}
回答by R.. GitHub STOP HELPING ICE
First, fix your kernel not to overcommit:
首先,修复你的内核不要过度使用:
echo "2" > /proc/sys/vm/overcommit_memory
Now malloc
should behave properly.
现在malloc
应该表现得很好。
回答by Ignacio Vazquez-Abrams
It happens when you try to allocate too much memory at once.
当您尝试一次分配过多内存时会发生这种情况。
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
void *p;
p = malloc(1024L * 1024 * 1024 * 1024);
if(p == NULL)
{
printf("%d\n", errno);
perror("malloc");
}
}
In your case the OOM killer is getting to the process first.
在您的情况下,OOM 杀手首先进入流程。
回答by Cacho Santa
I think errno
will be set to ENOMEM
:
我认为errno
将设置为ENOMEM
:
Macro defined in stdio.h
. Here is the documentation.
中定义的宏stdio.h
。这是文档。
#define ENOMEM 12 /* Out of Memory */
After you call malloc in this statement:
在此语句中调用 malloc 后:
myblock = (void *) malloc(MEGABYTE);
myblock = (void *) malloc(MEGABYTE);
And the function returns NULL
-because system is out of memory -.
该函数返回 -NULL
因为系统内存不足 -。
I found thisSO question very interesting.
我发现这个问题很有趣。
Hope it helps!
希望能帮助到你!
回答by blueshift
As "R" hinted, the problem is the default behaviour of Linux memory management, which is "overcommiting". This means that the kernel claims to allocate you memory successfuly, but doesn't actually allocate the memory until later when you try to access it. If the kernel finds out that it's allocated too much memory, it kills a process with "the OOM (Out Of Memory) killer" to free up some memory. The way it picks the process to kill is complicated, but if you have just allocated most of the memory in the system, it's probably going to be your process that gets the bullet.
正如“R”所暗示的,问题在于 Linux 内存管理的默认行为,即“过度使用”。这意味着内核声称已成功为您分配内存,但直到稍后您尝试访问它时才实际分配内存。如果内核发现它分配了太多内存,它会使用“OOM(内存不足)杀手”杀死进程以释放一些内存。它选择要杀死的进程的方式很复杂,但是如果您刚刚分配了系统中的大部分内存,则可能是您的进程获得了子弹。
If you think this sounds crazy, some people would agree with you.
如果你觉得这听起来很疯狂,有些人会同意你的看法。
To get it to behave as you expect, as R said:
为了让它像你期望的那样表现,正如 R 所说:
echo "2" > /proc/sys/vm/overcommit_memory
echo "2" > /proc/sys/vm/overcommit_memory