C 静态变量和 linux fork
您好,我创建了一个服务器程序,它在接受套接字连接后分叉一个新进程。 程序中定义了几个静态分配的全局变量。我的问题是这些静态缓冲区在分叉后分配了两次吗?或者fork仅复制堆和调用堆栈上的地址空间?
Hi I created a server program that forks a new process after its accepts a socket connection.
There are several statically allocated global variables defined in the program. My question is are these static buffers allocated twice after the fork? Or does the fork only duplicate address space on the heap and the call stack?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
整个地址空间都是重复的,包括所有全局变量和程序文本。
The entire address space is duplicated, including all global variables and the program text.
整个地址空间在
fork(2)
期间被“复制”。它通常通过写时复制来完成,并且有更多关于共享程序文本和库的详细信息,但这与这里无关。父进程和子进程最终都会得到自己的静态数据副本。The whole address space is "duplicated" during
fork(2)
. It's often done with copy-on-write and there are more details about sharing program text and the libraries, but that is not relevant here. Both parent and child processes end up with their own copy of the static data.fork()
复制整个进程映像。所有这一切。因此,它们是否分配了两次...不,它们为每个可执行映像分配一次,现在有两个可执行映像,不,如果您在父级中引用一个,它将不会包含与父级相同的内容除非你使用共享内存。在
static
上,该关键字的含义如下(来自 ISO C99):这基本上意味着您的缓冲区将作为 CRT 启动例程的一部分初始化一次,并且该空间仅在您退出时消失。在这种情况下,当每个孩子退出时,该存储就会消失。
fork()
duplicates the entire process image. All of it. As such, are they allocated twice... no, they're allocated once per executable image of which there are now two, and no, if you refer to one in the parent, it will not hold the same content as that of the child unless you use shared memory.On
static
, that keyword means this (from ISO C99):Which basically means your buffer will be initialised once as part of the CRT startup routine and that space only disappears when you exit. In this case, that storage disappears when each child exits.
Linux 使用称为写时复制的机制。这基本上意味着,只要变量没有被修改,父进程和新进程就共享一个变量。但在修改变量之前,它会被复制,并且新进程使用复制。这样做是出于性能原因,技术称为惰性优化。因此,您不必担心在一个进程中更改变量会在另一个进程中更改它。
Linux uses mechanism called copy-on-write. That basically means, that as long as variable is not modified parent and new process are sharing one variable. But before variable is modified it is copied and new process uses copy. It is done for performance reasons and technique is called lazy optimization. So you shouldn't worry that changing variable in one process will change it in another.