Does fork () duplicate all of the parent's memory?

Suppose I compile and run the fork () tutorial example.

#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main(void) { pid_t pid; pid = fork(); if (pid == -1) return 1; if (pid == 0) puts("From child process."); else puts("From parent process."); return 0; } 

Is the code obtained from both branches of the if (pid == 0) operator in fork() ? In other words, does the child process contain code intended for the parent that will never be executed by it and vice versa? Or maybe the / compiler optimizes this?

+5
source share
1 answer

fork() duplicates the whole process. The only difference is the return value of the fork() call itself - in the parent object it returns the child PID, in the child case it returns 0 .

Most operating systems optimize this using a method called copy on write. Instead of copying the entire memory, the child shares the parent memory. However, all memory pages are marked as "copy-on-write", which means that if any process modifies something on the page, it will be copied at this time, and the process that changed it will be changed to use copy (and the COW flag will also be disabled for the original page).

See Wikipedia for more details.

+7
source

All Articles