fork()是否复制父代的所有内存? [英] Does fork() duplicate all the memory of the parent?

查看:201
本文介绍了fork()是否复制父代的所有内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我编译并运行了fork()的教科书示例。

Suppose I compile and run the textbook example of fork().

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
        pid_t pid;
        pid = fork();

        if (pid == -1)
                return 1;

        if (pid == 0)
                puts("From child process.");
        else
                puts("From parent process.");

        return 0;
}

是否从的两个分支获取代码? pid == 0)语句得到 fork()吗?换句话说,子进程是否包含针对父进程的代码,而该代码将永远不会被其执行?还是编译器可以优化它?

Does the code from both branches of the if (pid == 0) statement get at fork()? In other words, does the child process contain code meant for the parent that will never be executed by it and vice versa? Or does/can the compiler optimize this?

推荐答案

fork()复制整个过程。唯一的区别是 fork()调用本身的返回值-在父级中,它返回子级的PID,在子级中,它返回 0

fork() duplicates the entire process. The only difference is in the return value of the fork() call itself -- in the parent it returns the child's PID, in the child it returns 0.

大多数操作系统使用称为写时复制的技术对其进行优化。孩子不共享所有内存,而是共享父母的内存。但是,所有内存页面都标记为写时复制,这意味着,如果任一进程修改了页面中的某些内容,则将在那个时候对其进行复制,并且修改了它的进程将更改为使用副本(以及COW

Most operating systems optimize this, using a technique called copy on write. Rather than copy all the memory, the child shares the parent's memory. However, all the memory pages are marked copy-on-write, which means that if either process modifies something in a page, it will be copied at that time and the process that modified it will be changed to use the copy (and the COW flag will be turned off for the original page as well).

请参阅复制时写了解更多信息。

Refer to the Wikipedia articles on fork and copy-on-write for more information.

这篇关于fork()是否复制父代的所有内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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