Fork() and global variable

十年热恋 提交于 2020-07-11 07:06:39

问题


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");
  }

}

回答1:


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

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




回答2:


When you fork, the child becomes a copy of the parent process. The copy of the variable in the child process is totally disconnected from the variable in the parent process.




回答3:


When you use fork, you create a different processus which do not share memory with the first one.

(You can see threads for that)



来源:https://stackoverflow.com/questions/48117670/fork-and-global-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!