0

Don't quite understand the output of the following C++ program.

#include <iostream>
#include <sys/types.h>

void foo(int *p) {
  std::cout << p << std::endl;
  (*p) ++;
}

int main() {
  int i = 100;
  if (fork() == 0) {
    foo(&i);
    std::cout << i << std::endl;
  } else {
    foo(&i);
    std::cout << i << std::endl;
  }
}

A sample output may be

0x10f273070
101
0x10f273070
101

Why the addresses are the same and output are both 101? I would expect one process outputs 101, the other outputs 102.

JAYS
  • 1
  • 1
    The address in one process is not same as address in another process. They are valid only in the context of the process. OS and CPU map these values to actual physical address (using tables in the process context) internally. In addition, variable address in physical memory doesn't change if you fork a process, unless you change their value, at which time a copy-on-write occurs, and the variable physical address in one forked process will differ from now on. – Ali Tavakol Oct 28 '20 at 06:22
  • Thanks! But one thing is fork seems to create a child process and run the code below itself. I can understand what you mean the address maps to different physical addresses for the two processes. But how do they both have value 100? They copy the values from physical address used by parent process to child process? – JAYS Oct 28 '20 at 06:35
  • The physical memory of the forked process is the exact physical memory of the parent one. no copy is made. unless child or parent change the value, at which time, the variable will be copied to a new physical memory location and change applies in this new location. – Ali Tavakol Oct 28 '20 at 06:39

2 Answers2

4

fork() clones a child process, it also clones the memory of the parent process so all variables in the child process have the same logical address and value as its parent process. If you update a variable after the fork(), it will be only updating the value of its own process. That's why you see both prints 101.

Tiger Yu
  • 744
  • 3
  • 5
1

On fork child process and the parent process run in separate memory spaces.

  1. Hence you will see the same data at parent and child process
  2. Address printed at both the processes are virtual and not a physical address
TruthSeeker
  • 1,539
  • 11
  • 24
  • Thanks! But one thing is fork seems to create a child process and run the code below itself. I can understand what you mean the address maps to different physical addresses for the two processes. But how do they both have value 100? They copy the values from physical address used by parent process to child process? – JAYS Oct 28 '20 at 06:37
  • yes, for details follow [this](https://stackoverflow.com/questions/7253659/why-the-address-of-variable-of-child-process-and-parent-process-is-same). Basically entire process memory is copied to child process hence all variable values remains same after forking. – TruthSeeker Oct 28 '20 at 06:39