I am programming a server daemon from which users can query data in C. The data can also be modified from clients.
I thought about keeping the data in memory.
For every new connection I do a fork().
First thing I thought about that this will generate a copy of the db every time a connection takes places, which is a waste of memory.
Second problem I have is that I don’t know how to modify the database in the parent process.
What concepts are there to solve these problems?
Just a few observations:
fork()only clones the memory of the process it executes at the time of execution. If you haven’t opened or loaded your database at this stage, it won’t be cloned into the child processes.mmap()andMAP_SHAREDwill be shared between processes and will not be duplicated.Aside On modern Linux systems,
fork()implements copy-on-write copying of process memory. Actually, you won’t end up with two copies of a process in memory – you’ll end up with one copy that believes it has been copied twice. If you write to any of the memory, then it will be copied. This is an efficiency saving that makes use of the fact that the majority of processes alter only a small fraction of their memory as they run, so in fact even if you went for the copy the whole database approach, you might find the memory usage less that you expect – although of course that wouldn’t fix your synchronisation problems!