3 ms·
fork would copy the entire address space of the process, which was wasteful when you're usually going to just throw all of that memory away by calling exec. BSD
by jmgao 11y ago
fork would copy the entire address space of the process, which was wasteful when you're usually going to just throw all of that memory away by calling exec. BSD added vfork to optimize the `if (fork() == 0) exec(...)` scenario, by not copying the memory, and just pausing and then borrowing memory from the parent, until exec is called. Modern operating systems use copy on write pages for fork, so instead of copying all of memory, you just need to copy the page tables.
- vram22 11y ago> then borrowing memory from the parent, until exec is called What does that mean?
- the_why_of_y 11y agoIt means that if the child process actually modifies the memory then those modifications will be visible in the parent process, because they're both using the same address space. It's essentially an awful hack that was added to BSD at a time when it didn't yet use copy-on-write for fork() to achieve the same performance with vfork()+exec() that you would get from a CreateProcess()-like API. That's why the child is allowed to do almost nothing: the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before success‐ fully calling _exit(2) or one of the exec(3) family of functions.
- vram22 11y agoThanks.