fork() & 内存分配行为

2024-04-20

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

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

如果我执行 fork() ,它会失败,因为内核也尝试为子进程分配 100 MB 的空间吗?

我读过 Linux 在分叉时使用写时复制,因此子进程和父进程共享所有页面。所以我想 fork 应该会成功?

假设 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将失败。它会失败,因为如果程序希望写入所有页面,则可能会取消共享其所有页面,而严格的过量使用模式将不允许这样做。

你可以替换fork with vfork那会起作用的。vfork被设计为仅在与exec在 fork/exec 模型中启动一个新进程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

fork() & 内存分配行为 的相关文章

随机推荐