gpt4 book ai didi

linux - 如果进程 malloc 内存然后 fork ,子进程是否会有适当的 malloced 内存

转载 作者:太空宇宙 更新时间:2023-11-04 08:59:51 25 4
gpt4 key购买 nike

对于以下代码:

main() {
int *p = (int *)malloc(2*sizeof(int)) ;
if(fork()) wait() ;
else *p = 10 ;
}

我想知道当我们 fork 时,子进程是否也在其进程空间中接收到 malloced block 。也就是说,在上面的代码中可以安全地说 --:

*p = 10 ;

最佳答案

是的, child 将拥有适当的 malloc()ed 内存。

首先,知道有两个内存管理器:

也就是说,malloc() 对内存所做的操作对 Linux 内核是完全透明的。它实际上只是一两个链表,您可以自己实现。 Linux 内核将内存视为分配给进程的页面及其内容。

当您调用 fork() 时(强调我的):

  • The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.
  • The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).
  • The child inherits copies of the parent's set of open message queue descriptors (see mq_overview(7)). Each descriptor in the child refers to the same open message queue description as the corresponding descriptor in the parent. This means that the two descriptors share the same flags (mq_flags).
  • The child inherits copies of the parent's set of open directory streams (see opendir(3)). POSIX.1-2001 says that the corresponding directory streams in the parent and child may share the directory stream positioning; on Linux/glibc they do not.

所以 fork() 不仅复制了整个虚拟地址空间,而且还复制了所有互斥体、文件描述符以及父进程打开的几乎所有资源。复制的部分虚拟地址空间是 malloc() 的链表。所以在 fork() 之后,两个进程的 malloc()ed 内存是相等的,malloc() 保留的信息以及内存是什么分配也是一样的。但是,它们现在位于单独的内存页面上。


补充信息:有人可能认为 fork() 是一项非常昂贵的操作。但是(来自手册页):

Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

这基本上是说,在 fork()ing 上,没有完成实际的复制,但是页面被标记为要复制,如果 child 试图修改它们。实际上,如果 child 只从该内存中读取,或完全忽略它,则没有复制开销。这对于常见的fork()/exec() 非常重要。模式。

关于linux - 如果进程 malloc 内存然后 fork ,子进程是否会有适当的 malloced 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23608033/

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