Here is my code:
#include <stdio.h>
#include <unistd.h>
static volatile int t=0;
int main(void){
int i;
for (i=0; i<2; i++){
fork();
printf("pid:%d: addr:%d val:%d\n", getpid(), &t, t++);
}
printf("pid:%d: addr:%d val:%d\n", getpid(), &t, t++);
return 0;
}
the output like that:
pid:16232: addr:134518684 val:0
pid:16233: addr:134518684 val:0
pid:16232: addr:134518684 val:1
pid:16232: addr:134518684 val:2
pid:16234: addr:134518684 val:1
pid:16234: addr:134518684 val:2
pid:16233: addr:134518684 val:1
pid:16233: addr:134518684 val:2
pid:16235: addr:134518684 val:1
pid:16235: addr:134518684 val:2
The address of global variable t is same, does all threads operate the same variable t? I expect the val was “0, 1, 2, 3, 4, 5, …”, how should I do?
The results are correct. That’s because, when forking, you create a new process that gets a copy of the parent process memory.
The addresses you see are virtual, so, even though they are the same, that doesn’t mean they are pointing at the same physical memory zones.