为什么fork()使用相同的变量但值不同?

Ros*_*ose 5 c++ fork c++11

这是代码:

#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){
} 
Run Code Online (Sandbox Code Playgroud)

这是结果:

--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--
Run Code Online (Sandbox Code Playgroud)

显然在子进程中,它是具有相同地址的相同参数,但值不同.

为什么会这样?

Lig*_*ica 10

每个进程都有自己的虚拟内存空间.

这意味着0x7ffc9b01c6a4在一个过程中与0x7ffc9b01c6a4另一个过程完全无关.

这不是同一个对象; 它是新流程中的一个对象.由于第二个进程是从第一个进程分叉出来的,基本上是克隆进程,所以对象应该存在于第二个进程中的第二个进程中,与第一个进程相同,这并不奇怪.