Search code examples
cfork

Fork() and global variable


i know that when two variable have same address they gonna have the same value but in my case the var " a " have same address in child and parent process after fork .. but when i set a = 1 in child process the value of a in father process stay 5 ... why ? and thanks


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int a = 5;

int main(int argc, char const *argv[]) {

  pid_t pid;
  pid = fork();
  if (pid == -1) {
    printf("%s\n", " erreur while creating fils !");

  } else if (pid == 0){
      a = 1;
      printf("%s %d\n", "child", a);
      printf("%s %p\n", "child", &a);
      return printf("child done\n");
  } else {
    wait(0);
    printf("%s %d\n", "father", a);
    printf("%s %p\n", "father", &a);
    return printf("father done\n");
  }

}

Solution

  • Parent and child processes have different address spaces after fork().

    enter image description here

    Even if you use global variable, it's copied. When you try to change it, its copy value is changed.

    they still have the same memory address.. why ?

    There is a disconnection between physical memory and the virtual address space of a process. It seems same memory addresses there, that's only the virtual address. For more, 4G address space and mapping