Search code examples
clinuxunixpipefork

Within child and parent processes, variables has same addresses but have different value?


#include <stdio.h>
#include <unistd.h>

int main() {
    int x = 0;
    pid_t pid = fork();
    if(pid == 0) {
        //adding one to X when it is child process
        x++;
    }
    printf("current X: %d, address of X: %p, process : %d\n", x, &x, pid);
}

the result is: result

So I am new to the Unix and not really familiar with the fork(). If the child process will make a copy of the parent process so that it will have different address spaces. Then, why X on both processes here have the same address but different value?


Solution

  • That is how fork works. It makes a copy of the address-space, actually it makes some optimizations (only changed pages have to be written).

    The copy uses the same addresses:

    • this is possible because the parent and child process will each only see their version

    • and it is required: if you have any linked datastructure, the pointers from one object to another have to remain valid. If the copied address space would occupy different addresses then all pointers would have to be fixed - and the operating system does not even know which of the bytes are pointers and which are just data.