C 静态变量和 linux fork

发布于 2024-10-15 17:57:47 字数 104 浏览 3 评论 0原文

您好,我创建了一个服务器程序,它在接受套接字连接后分叉一个新进程。 程序中定义了几个静态分配的全局变量。我的问题是这些静态缓冲区在分叉后分配了两次吗?或者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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

百合的盛世恋 2024-10-22 17:57:47

整个地址空间都是重复的,包括所有全局变量和程序文本。

The entire address space is duplicated, including all global variables and the program text.

谢绝鈎搭 2024-10-22 17:57:47

整个地址空间在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.

颜漓半夏 2024-10-22 17:57:47

fork() 复制整个进程映像。所有这一切。因此,它们是否分配了两次...不,它们为每个可执行映像分配一次,现在有两个可执行映像,不,如果您在父级中引用一个,它将不会包含与父级相同的内容除非你使用共享内存。

static 上,该关键字的含义如下(来自 ISO C99):

声明了标识符的对象
具有外部或内部链接,或
与存储类别说明符
static 具有静态存储持续时间。
它的生命周期是整个执行过程
程序及其存储值是
仅在之前初始化一次
程序启动。

这基本上意味着您的缓冲区将作为 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):

An object whose identifier is declared
with external or internal linkage, or
with the storage-class specifier
static has static storage duration.
Its lifetime is the entire execution
of the program and its stored value is
initialized only once, prior to
program startup.

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.

情深缘浅 2024-10-22 17:57:47

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文