I have known that parent and child have different address spaces but when i ran the below code and check the address of a variable in parent and child, it came out to be same. As if both the variable name is for same memory location why didn't the change in value by child is reflected back in parent.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int turn = 0;
if (fork() == 0)
{
turn = 10;
printf("Child Turn: %d\n", turn);
printf("Child Address of turn: %p\n", &turn);
exit(0);
}
else
{
sleep(2);
printf("Parent Turn: %d\n", turn);
printf("Parent Address of turn: %p\n", &turn);
}
return 0;
}
Output is:
Child Turn: 10
Child Address of turn: 0xbfc1830c
Parent Turn: 0
Parent Address of turn: 0xbfc1830c
If both have same address why value different. Or it is something like for example
If we have two boxes one named parent and one child.
Both the boxes contain numbers 1 to 10.
So in child box also we have say number 5,
and in parent box also we have number 5.
The number is same but in different boxes.
Similar in the above case the address is same 0xbfc1830c, but in different process address spaces. Is it like this.