gpt4 book ai didi

c - Fork() 和全局变量

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:45 24 4
gpt4 key购买 nike

我知道当两个变量具有相同的地址时,它们将具有相同的值,但在我的例子中,var“a”在 fork 之后的子进程和父进程中具有相同的地址..但是当我在子进程中设置 a = 1 时父进程中 a 的值保持 5 ... 为什么?并感谢


#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()之后有不同的地址空间。

enter image description here

即使您使用全局变量,它也会被复制。当您尝试更改它时,它的复制值已更改。

they still have the same memory address.. why ?

进程的物理内存和虚拟地址空间之间存在断开连接。那里似乎有相同的内存地址,那只是虚拟地址。更多信息,4G address space and mapping

关于c - Fork() 和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48117670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com