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?
Aucun commentaire:
Enregistrer un commentaire