Linux – When a process forks is its virtual or resident memory copied

forklinuxlinux-kernelmemory

The standard way of making new processes in Linux is that the memory footprint of the parent process is copied and that becomes the environment of the child process until execv is called.

What memory footprint are we talking about, the virtual (what the process requested) or the resident one (what is actually being used)?

Motivation: I have a device with limited swap space and an application with a big difference between virtual and resident memory footprint. The application can't fork due to lack of memory and would like to see if trying to reduce the virtual footprint size would help.

Best Answer

In modern systems none of the memory is actually copied just because a fork system call is used. It is all marked read only in the page table such that on first attempt to write a trap into kernel code will happen. Only once the first process attempt to write will the copying happen.

This is known as copy-on-write.

However it may be necessary to keep track of committed address space as well. If no memory or swap is available at the time the kernel has to copy a page, it has to kill some process to free memory. This is not always desirable, so it is possible to keep track of how much memory the kernel has committed to.

If the kernel would commit to more than the available memory + swap, it can give an error code on attempt to call fork. If enough is available the kernel will commit to the full virtual size of the parent for both processes after the fork.