Linux中父进程及其子进程的地址空间之间的区别? [英] Difference between the address space of parent process and its child process in Linux?

查看:900
本文介绍了Linux中父进程及其子进程的地址空间之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此我感到困惑.我读过,当父进程创建一个孩子时, 子级获得其父级地址空间的副本.复制在这里意味着什么? 如果我使用下面的代码,那么它会打印出变量"a"的相同地址,所有变量都在堆上 案件.即在孩子和父母的情况下.那么,这是怎么回事?

I am confused about it. I have read that when a child is created by a parent process, child gets a copy of its parent's address space. What it means here by copy? If i use code below, then it prints same addresses of variable 'a' which is on heap in all cases. i.e in case of child and parent. So what is happening here?

int main () { pid_t pid; int *a = (int *)malloc(4); printf ("heap pointer %p\n", a); pid = fork(); if (pid < 0) { fprintf (stderr, "Fork Failed"); exit(-1); } else if (pid == 0) { printf ("Child\n"); printf ("in child heap pointer %p\n", a); } else {

int main () { pid_t pid; int *a = (int *)malloc(4); printf ("heap pointer %p\n", a); pid = fork(); if (pid < 0) { fprintf (stderr, "Fork Failed"); exit(-1); } else if (pid == 0) { printf ("Child\n"); printf ("in child heap pointer %p\n", a); } else {

}

推荐答案

子级将获得父级地址空间的精确副本,在许多情况下,该地址很可能以与父级地址空间相同的格式进行布局.我必须指出,每个内存都将拥有自己的虚拟地址空间,这样每个内存可以在相同地址但在不同地址空间中拥有相同数据.另外,Linux在创建子进程时使用写时复制.这意味着父级和子级将共享父级地址空间,直到其中之一进行写操作为止,此时,内存将被物理复制到子级. exec进行新处理时,这消除了不需要的副本.既然您将要用新的可执行文件覆盖内存,为什么还要麻烦复制它?

The child gets an exact copy of the parents address space, which in many cases is likely to be laid out in the same format as the parent address space. I have to point out that each one will have it's own virtual address space for it's memory, such that each could have the same data at the same address, yet in different address spaces. Also, linux uses copy on write when creating child processes. This means that the parent and child will share the parent address space until one of them does a write, at which point the memory will be physically copied to the child. This eliminates unneeded copies when execing a new process. Since you're just going to overwrite the memory with a new executable, why bother copying it?

这篇关于Linux中父进程及其子进程的地址空间之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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