address space after fork call

只谈情不闲聊 提交于 2020-01-11 11:56:14

问题


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 ***\n");
        printf(" Address is %p\n",ptr);
        printf(" char value is %c\n",y);
        sleep(5);
    }
    else
    {
        sleep(5);
        printf("\n ***parent process ***\n",&y);
        printf(" Address is %p\n",ptr);
        printf(" char value is %c\n",y);
    }
}

and its output:

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

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

回答1:


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'

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




回答2:


According to me after u run 'execve' command u will see the difference. Until then child shares same image and space as of parent.



来源:https://stackoverflow.com/questions/13185917/address-space-after-fork-call

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