gpt4 book ai didi

linux - fork() 中的写时复制如何处理多个 fork ?

转载 作者:IT王子 更新时间:2023-10-28 23:34:02 26 4
gpt4 key购买 nike

根据维基百科(可能是错误的)

When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an "exec" system call (which is used to execute any executable file from within a C program) or exits very soon after the fork(). When the child is needed just to execute a command for the parent process, there is no need for copying the parent process' pages, since exec replaces the address space of the process which invoked it with the command to be executed.

In such cases, a technique called copy-on-write (COW) is used. With this technique, when a fork occurs, the parent process's pages are not copied for the child process. Instead, the pages are shared between the child and the parent process. Whenever a process (parent or child) modifies a page, a separate copy of that particular page alone is made for that process (parent or child) which performed the modification. This process will then use the newly copied page rather than the shared one in all future references. The other process (the one which did not modify the shared page) continues to use the original copy of the page (which is now no longer shared). This technique is called copy-on-write since the page is copied when some process writes to it.

似乎当任何一个进程尝试写入页面时。页面的新副本被分配并分配给产生页面错误的进程。原始页面随后被标记为可写。

我的问题是:如果在任何进程尝试写入共享页面之前多次调用 fork 会发生什么?

最佳答案

如果 fork 从原始父进程多次调用,则每个子进程和父进程都将其页面标记为只读。当子进程尝试写入数据时,父进程的页面将被复制到其地址空间,并且复制的页面在子进程中被标记为可写但在父进程中不可写。

如果从子进程调用 fork 并且孙子进程尝试写入,则原始父进程的页面将被复制到第一个子进程,然后再复制到孙子进程,一切都是标记为可写。

关于linux - fork() 中的写时复制如何处理多个 fork ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13813636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com