0

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
shanker861
  • 619
  • 1
  • 5
  • 9
  • 3
    Please do some research about *virtual memory*, and understand that each process have a separate and distinct memory map. – Some programmer dude Nov 18 '18 at 17:37
  • 1
    Reading the first few paragraphs of [fork(2) - Linux Programmer's Manual](http://man7.org/linux/man-pages/man2/fork.2.html) should answer your questions. – David C. Rankin Nov 18 '18 at 17:48
  • Thanks David & Melpomene, the man page and https://stackoverflow.com/questions/4594329/difference-between-the-address-space-of-parent-process-and-its-child-process-in helped a lot. – shanker861 Nov 18 '18 at 18:02

0 Answers0