I am trying to understand fork() functionality with following program. This may sound similar to fork() and changing local variables? but after observing address of variables, I could not convince myself that I understood it properly.
void forkexample()
{
int x = 1;
if (fork() == 0) {
++x;
printf("Child has x = %p, ' ',%d \n", &x,x);
}
else{
x += 2;
printf("Parent has x = %p, ' ',%d \n", &x,x);
}
}
int main()
{
forkexample();
return 0;
}
Sample output:
Parent has x = 0x7ffff25e71f4, ' ',3
Child has x = 0x7ffff25e71f4, ' ',2
My question is if both child and parent process are modifying same address, how come child still sees the value of 2 after parent has set it to 3.