分叉后的变量 [英] Variables after fork

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

问题描述

这是一个代码:

int i = 0;
pid_t pid;
puts("Hello, World!");
puts("");
pid = fork();
if (pid) {
    i = 42;
}   
printf("%p\n", &i);
printf("%d\n", i);
puts("");

并输出

Hello, World!

0x7fffc2490278
42

0x7fffc2490278
0

程序打印您好,世界!一次,子进程不是从头开始,也不是重新定义变量.变量的地址相同.因此,它们是相同的.但是我更改了首先执行的父流程中的值,但对于子流程未更改.为什么?

Program print Hello, World! one time, so child process wasn't start from the beginning and it wasn't re-define variables. Adresses of variables are same. So they are same. But I change i's value in parent process which is executed first, it didn't change for child process. Why?

推荐答案

变量的地址相同.所以他们是一样的.但是我更改了首先执行的父流程中的值,但对于子流程未更改.为什么?

Adresses of variables are same. So they are same. But I change i's value in parent process which is executed first, it didn't change for child process. Why?

地址在进程范围内.它们是虚拟地址.父进程中的地址0x7fffc2490278和子进程中的0x7fffc2490278是不同的物理地址.

The addresses are in the scope of a process. They are virtual addresses. Address 0x7fffc2490278 in the parent process and 0x7fffc2490278 in the child process are different physical addresses.

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

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