分叉调用后的地址空间 [英] address space after fork call

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

问题描述

当进程执行 fork() 系统调用时,会从中生成一个子进程.fork() 调用之后的所有代码都被复制到新的内存物理页,即帧.我无法可视化子进程的虚拟内存部分.因为在下面的代码中,char 变量的地址在子进程和父进程中是相同的.

When fork() sys call is executed by the process, a child process generated from it. All the codes following the fork() call is copied to the new physical pages of memory i.e frames. I am not able to visualize the virtual memory part of the child process.because in the following code the address of char variable is same in child as well as parent.

#include <stdio.h>
#include <sys/types.h>

int main(void)
{
    pid_t pid;
    char y='Y';
    char *ptr;
    ptr=&y;
    pid = fork();
    if (pid == 0)
    {
        y='Z';
        printf(" *** Child process ***
");
        printf(" Address is %p
",ptr);
        printf(" char value is %c
",y);
        sleep(5);
    }
    else
    {
        sleep(5);
        printf("
 ***parent process ***
",&y);
        printf(" Address is %p
",ptr);
        printf(" char value is %c
",y);
    }
}

及其输出:

*** Child process ***
Address is 69002894
char value is Z

***parent process ***
Address is 69002894
char value is Y

推荐答案

两个进程的虚拟地址相同,但物理地址不同.您的进程只允许访问虚拟内存.在具有虚拟内存功能的机器中,内存管理单元将虚拟地址转换为物理地址.

The virtual address is the same in both processes, but the physical addresses are different. Your process is only allowed to access virtual memory. In machines with virtual memory capability, the memory management unit translates virtual addresses into physical addresses.

通常,操作系统使用写时复制方案来实现分叉.这意味着它们将具有相同的物理地址,直到有东西试图写入内存页面.当你放:

Usually, operating systems use a copy-on-write scheme to implement the forking. That means they will have the same physical addresses until something tries to write to the memory page. When you put:

y = 'Z'

操作系统复制了 y 所在的内存页并将该虚拟地址重新分配给新的物理地址.

The operating system copied the memory page that y was in and reassigned that virtual address to the new physical address.

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

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