Copy-On-Write:父子修改页面后的状态是什么?

时间:2015-04-14 10:36:38

标签: memory fork virtual-memory copy-on-write page-tables

当你分叉一个进程时,在开始时,父子共享相同的内存页面。但是,如果其中一个人在此页面上书写,那么它就会重复,以便第一个不受此更改的影响。这大致就是所谓的Copy-on-Write。

我的问题是:如果我们fork()一个进程,然后孩子修改页面会发生什么:页面重复一次,但之后,父亲也修改页面。页面是否再次重复?父亲“知道”只有儿子已经重复吗?

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

(通用存在过度简化的风险 - IE如何工作)

Parent process has Virtual Page 10 as readwrite physical page 1000.
Parent process has Virtual Page 11 as readwrite physical page 1001.

父母要求孩子。

Parent process has Virtual Page 10 as readonly physical page 1000.
Parent process has Virtual Page 11 as readonly physical page 1001.
Child process has Virtual Page 10 as readonly physical page 1000.
Child process has Virtual Page 11 as readonly physical page 1001.

父写入虚拟页面10。 触发保护错误。 操作系统检测到它是写入页面上的副本 将物理页面1000复制到1002 将引用计数减少到物理页面1000 重启指令

Parent process has Virtual Page 10 as readwrite physical page 1002.
Parent process has Virtual Page 11 as readonly physical page 1001.
Child process has Virtual Page 10 as readonly physical page 1000.
Child process has Virtual Page 11 as readonly physical page 1001.

儿童写入虚拟页面11 触发保护错误。 操作系统检测到它是写入页面上的副本 将物理页面1001复制到1003 将引用计数减少到物理页面1001 重启指令

Parent process has Virtual Page 10 as readwrite physical page 1002.
Parent process has Virtual Page 11 as readonly physical page 1001.
Child process has Virtual Page 10 as readonly physical page 1000.
Child process has Virtual Page 11 as readwrite physical page 1003.

父写入虚拟页面11 触发保护错误。 操作系统检测到它是写入页面上的副本并且引用计数为1。 操作系统将页面更改为readwrite 重启指令

Parent process has Virtual Page 10 as readwrite physical page 1002.
Parent process has Virtual Page 11 as readwrite physical page 1001.
Child process has Virtual Page 10 as readonly physical page 1000.
Child process has Virtual Page 11 as readwrite physical page 1003.

答案 1 :(得分:0)

有n个进程可以访问写入时复制页面,n≥2。如果一个进程写入,页面将被复制并成为该进程的正常页面。原始页面现在只共享n-1次;如果n = 1,那么它也成为正常页面。制作两份副本毫无意义。