As the parent process is using huge mount of memory, fork
may fail with errno
of ENOMEM
under some configuration of kernel overcommit policy. Even though the child process may only exec
low memory-consuming program like ls.
To clarify the problem, when /proc/sys/vm/overcommit_memory is configured to be 2, allocation of (virtual) memory is limited to SWAP + MEMORY * ration(default to 50%)
.
When a process forks, virtual memory is not copied thanks to COW. But the kernel still need to allocate virtual memory space. As an analogy, fork is like malloc(virtual memory space size) which will not allocate physical memory and writing to shared memory will cause copy of virtual memory and physical memory is allocated. When overcommit_memory is configured to be 2, fork may fail due to virtual memory space allocation.
Is it possible to fork
a process without inherit virtual memory space of parent process in the following conditions?
if the child process calls
exec
afterfork
if the child process doesn't call
exec
and will not using any global or static variable from parent process. For example, the child process just do some logging then quit.
This is possible on Linux. Use the
clone
syscall without the flagCLONE_THREAD
and with the flagCLONE_VM
. The parent and child processes will use the same mappings, much like a thread would; there is no COW or page table copying.