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?
相关问题
- Multiple sockets for clients to connect to
- What uses more memory in c++? An 2 ints or 2 funct
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
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.The entire address space is duplicated, including all global variables and the program text.
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 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.