Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fork() use the same variable but different value?

Tags:

c++

fork

c++11

Here's the code:

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

void f(int&);
void g(int&);

int main(int argc, char **argv)
{
    printf("--beginning of program\n");

    int counter = 0;
    pid_t pid = fork();
    if (pid == 0) {
        f(counter);
        printf("child process: %d, %p", counter, &counter);
    } else if (pid>0) {
        g(counter);
        for (int i=0; i<5; ++i) {
            sleep(1);
            printf("parent process: %d, %p\n", counter, &counter);
        }
    }
    printf("--end of program--\n");
    return 0;
}

void f(int& counter) {
    counter = 1;
    printf("in f: %d, %p-\n", counter, &counter);
}
void g(int& counter){
} 

and here's the result:

--beginning of program
in f: 1, 0x7ffc9b01c6a4-
child process: 1, 0x7ffc9b01c6a4--end of program--
parent process: 0, 0x7ffc9b01c6a4
parent process: 0, 0x7ffc9b01c6a4
parent process: 0, 0x7ffc9b01c6a4
parent process: 0, 0x7ffc9b01c6a4
parent process: 0, 0x7ffc9b01c6a4
--end of program--

Clearly in child process it's the same parameter with the same address, but the value is different.

Why is it happening?

like image 933
Rose Avatar asked Sep 24 '15 12:09

Rose


1 Answers

Each process has its own virtual memory space.

That means 0x7ffc9b01c6a4 in one process is entirely unrelated to 0x7ffc9b01c6a4 in another.

This is not the same object; it's an object in the new process. Since the second process was forked from the first one, essentially cloning the process, it's not a surprise that objects should exist in the same virtual memory location in the second as they were in the first.

like image 56
Lightness Races in Orbit Avatar answered Oct 13 '22 00:10

Lightness Races in Orbit