C static variables and linux fork

2019-02-13 02:59发布

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?

4条回答
Rolldiameter
2楼-- · 2019-02-13 03:26

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.

查看更多
相关推荐>>
3楼-- · 2019-02-13 03:32

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

查看更多
相关推荐>>
4楼-- · 2019-02-13 03:32

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.

查看更多
做个烂人
5楼-- · 2019-02-13 03:34

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.

查看更多
登录 后发表回答