Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Suppose I compile and run the textbook example of fork().

#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;
}

Does the code from both branches of the if (pid == 0) statement get at fork()? In other words, does the child process contain code meant for the parent that will never be executed by it and vice versa? Or does/can the compiler optimize this?

like image 464
nebuch Avatar asked Aug 21 '15 01:08

nebuch


1 Answers

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

Most operating systems optimize this, using a technique called copy on write. Rather than copy all the memory, the child shares the parent's memory. However, all the memory pages are marked copy-on-write, which means that if either process modifies something in a page, it will be copied at that time and the process that modified it will be changed to use the copy (and the COW flag will be turned off for the original page as well).

Refer to the Wikipedia articles on fork and copy-on-write for more information.

like image 67
Barmar Avatar answered Sep 18 '22 10:09

Barmar