Reputation: 89
#include<stdio.h>
int giCtr0;
int main(void){
int iPid;
iPid = fork();
if (iPid == 0){
giCtr0++;
printf("In Child\n");
printf("Addr\t%x Value\t%d\n",&giCtr0,giCtr0);
}
else{
giCtr0+=2;
printf("In Parent\n");
printf("Addr\t%x Value\t%d\n",&giCtr0,giCtr0);
}
return 0;
}
The output from Ubuntu is as follows:
In Parent
Addr 601054 Value 2
In Child
Addr 601054 Value 1
The Value is proper and as expected. How does address of the variable remain same in child and parent process? Is there anything wrong in this code? Please suggest.
Upvotes: 1
Views: 54
Reputation: 126167
Memory addresses in a Unix-like VM system are per-process. The address you obtain with the C &
operator is an OS-level construct, not the addressing scheme that maps directly to bits in RAM chips (or swapped-out VM pages). Thus, it's possible for the same address in two different processes to refer to two different locations in "real" memory.
fork
spawns a clone of the parent process. For both processes to continue operating as they had before the fork
, the entire memory image of the parent process is copied to create that of the child process... so, from each process' perspective, the memory addresses of all variables still point to the same things they did before. (But since the processes are now separate, changes in one affect a different underlying storage than is used by the other.)
Upvotes: 3
Reputation: 12006
How does address of the variable remain same in child and parent process?
To add to the comment from mkimball
Linux implements virtual memory. That means it sets up the hardware so each process sees a 'virtual' memory map instead of the 'real'/physical memory map.
Because of this the memory address 0x601054
of one process does not necessarily correspond to the same real memory 'cell' as the same address 0x601054
inside another process.
Upvotes: 2