c - 子进程与父进程的地址空间?

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

问题描述

问 题

看到过一段描述

fork()被包含在unistd.h中。这个函数不需要任何参数;它会直接创建一个新的进程,将现在运行的进程的处理器状态、地址空间直接拷贝到新进程中,因此新进程也会从fork()对应的指令开始运行。


这里提到了子进程拷贝父进程的地址空间, 但是我记得看到过每个进程的地址空间都是唯一的, 查了下,

The process address space is described by the mm_struct struct meaning that only one exists for each process and is shared between userspace threads.

  • 这个链接也指出只有线程才拥有相同的地址空间

Modern virtual memory operating systems generally have a flat memory model and not a segmented one. Normally, this flat address space is unique to each process. A memory address in one process's address space tells nothing of that memory address in another process's address space. Both processes can have different data at the same address in their respective address spaces. Alternatively, processes can elect to share their address space with other processes. We know these processes as threads.

最后在sf上遇到这个问题

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?

不过这个答案还是有些地方我没有理解,

我的现在的想法是这样的

  1. 子空间本身有着和父进程不同的地址空间

  2. 但是同时拥有者父进程地址空间的副本.

我想在这里确认下, 我的这两点想法有没有问题?

解决方案

你的理解没问题。就好像两个单元房间内的布局是一样的,但还是两个不同的房间。写复制(copy-on-write)只是一个性能优化,用户看到的永远是两个独立的空间。

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

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