fork()和内存分配行为

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

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

如果我做了一个fork(),它会失败,因为内核试图为子进程分配100 MB?

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

假设fork成功了,可以说我在调用exec()之前在子进程中有几行代码。 所以父母和孩子将继续共享文本段,除非子进程触及任何堆内存,否则内存使用情况不应有任何变化。 它是否正确 ?

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

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

你可以用vfork替换fork ,那就行了。 vfork的设计目的只有在与fork / exec模型中的exec结合起来才能启动新进程。

链接地址: http://www.djcxy.com/p/71617.html

上一篇: fork () & memory allocation behavior

下一篇: The difference between fork(), vfork(), exec() and clone()