fork()&内存分配行为

时间:2012-10-16 21:53:57

标签: linux memory-management linux-kernel fork

我在禁用交换且禁用内存过量使用的系统上工作。

假设我的进程当前消耗100 MB内存,系统可用内存小于100 MB。

如果我执行fork()会失败,因为内核也试图为子进程分配100 MB?

我已经读过Linux在分叉时使用了copy-on-write,因此child&父母分享所有页面。所以我猜叉子应该成功吗?

假设fork成功,假设我在调用exec()之前在子进程中有几行代码。所以父母& child将继续共享文本段,除非子进程触及任何堆内存,否则不应对内存使用情况进行任何更改。这是对的吗?

Edit: One follow-up question: With swapping/overcommit disabled, can the cumulative VSS 
(Virtual Set Size) of all the processes be more than the available physical memory ?

I tried this out.  VSS of all the processes can be much more than that of the physical 
memory available.

pmap -x output from a process. 

total kB          132588   10744    7192

First number - Virtual Set Size
Second number - Resident Set Size
third number - dirty pages

RSS is < 10% of VSS. This is with swapping and overcommit disabled.

For every shared library loaded I see something like the following..

00007fae83f07000      32      24       0 r-x--  librt-2.12.so
00007fae83f0f000    2044       0       0 -----  librt-2.12.so
00007fae8410e000       8       8       8 rw---  librt-2.12.so

00007fae84312000     252     120       0 r-x--  libevent-2.0.so.5.0.1
00007fae84351000    2048       0       0 -----  libevent-2.0.so.5.0.1
00007fae84551000       8       8       8 rw---  libevent-2.0.so.5.0.1

I guess r-x segment is code and rw- is data. But there is a 2 MB segment 
that is not loaded. I see this 2 MB segment for every single shared library. 
My process loads a lot of shared libraries. That explains the huge difference 
between VSS & RSS.

Any idea what is that 2 MB segment per shared library ? 

When overcommit is disabled, if this process calls fork() will it fail when 
the free memory is less than VSS (132588 Kb) or RSS (10744) ?

1 个答案:

答案 0 :(得分:0)

是的,如果完全禁用内存过量使用,则fork将失败。它会失败,因为程序可能会取消共享所有页面,如果它希望写入它们,严格的过度使用模式将不允许这样做。

您可以将fork替换为vfork,这样可行。 vfork旨在仅在与fork / exec模型中的exec结合使用时才能使用,以启动新流程。