Search code examples
unixprocessexecfork

Is the unix fork exec sequence really as expensive as it sounds?


I'm reading about fork and exec for an exam, and my book says that whenever it is needed to run a new (different) process in unix systems, you would fork the current process followed by an execve.

However, it also says that whenever fork is called, the whole memory image of the parent is copied to the new process.

Then my question is: What if you have a process with a really big memory image, and you just want to run a new process? Isn't it a waste of resources to copy all the data from the parent process if you are just going to replace it immediately?


Solution

  • Usually the fork does not actually copy all the memory, but uses a "copy on write" which means that as long as the memory is not modified the same pages are used. However, to avoid not having enough memory later on (should the process write to the memory) enough memory must be allocated.

    This means that forking from large process on systems that do not allow overcommitting memory the memory must be available. So, if you have a 8 GB process forking, then for at least a short period of time 16 GB must be available.

    See also vfork and posix_spawn for other solutions.