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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With