c - fork 失败 : Cannot allocate memory

标签 c linux system fork out-of-memory

我有一个在 linux 机器上运行的程序。它 fork 一个进程来发送邮件,并经常记录 fork 失败消息,指出它无法分配内存。

当我检查驻留内存的大小时,它大约为 12Gb(交换在这台机器上配置为只有 1Gb)。

有什么方法可以确定这一大块内存不是泄漏,而只是内存增长?

此外,是否存在可以调整的系统限制,以便我不会遇到任何 fork 失败?

最佳答案

要检查内存泄漏,您可能希望在 Valgrind 下运行该程序:http://valgrind.org


要从控制台/shell 获取/设置限制,可以使用 ulimit 命令。

在程序内部,系统调用 getrlimit()/setrlimit() 提供此功能。


对于内存可能由于 fork()ing 变得紧张的情况,另一种解决方法是立即使用 vfork(),然后调用 exec*() 函数族。

来自 man vfork:

vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance-sensitive applications where a child is created which then immediately issues an execve(2).

vfork() differs from fork(2) in that the parent is suspended until the child terminates (either normally, by calling _exit(2), or abnormally, after delivery of a fatal signal), or it makes a call to execve(2). Until that point, the child shares all memory with its parent, including the stack. The child must not return from the current function or call exit(3), but may call _exit(2).

关于c - fork 失败 : Cannot allocate memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374399/

相关文章:

c - GCC:为什么 const 数据填充在我的函数内部而不是开头?

c - 线性搜索代码显示我的项目不存在。请帮我更正

linux - 就地执行时与 sed 的不同行为

linux - 存储网络数据包

用于设置 pagefile.sys 大小的 PowerShell 脚本

C++:如何使我的程序打开带有可选参数的.exe

c - 在文件流中后退一位

c++ - 语句内的等号/赋值运算符

linux - 为什么 clock_gettime(CLOCK_REALTIME, ..) 上的调用延迟变化如此之大?

algorithm - 如何解决不平等制度?