Fork()和全局变量 [英] Fork() and global variable

查看:147
本文介绍了Fork()和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,当两个变量具有相同的地址时,它们将具有相同的值,但是在我的情况下,var"a"在fork和子进程中的子进程和父进程中具有相同的地址.但是当我在子进程中设置a = 1时,一个父亲进程的价值停留5 ...为什么?谢谢

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

}

推荐答案

父进程和子进程在fork()之后具有不同的地址空间.

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 ?

物理内存与进程的虚拟地址空间之间存在断开连接.那里似乎有相同的内存地址,那只是虚拟地址.有关更多信息,请 4G地址空间和映射

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

这篇关于Fork()和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆