I am working on implementing a database server in C that will handle requests from multiple clients. In order to do so I am using fork() to handle connections for individual cli
First of all, fork
is completely inappropriate for what you're trying to achieve. Even if you can make it work, it's a horrible hack. In general, fork
only works for very simplistic programs anyway, and I would go so far as to say that fork
should never be used except followed quickly by exec
, but that's aside from the point here. You really should be using threads.
With that said, the only way to have memory that's shared between the parent and child after fork
, and where the same pointers are valid in both, is to mmap
(or shmat
, but that's a lot fuglier) a file or anonymous map with MAP_SHARED
prior to the fork
. You cannot create new shared memory like this after fork
because there's no guarantee that it will get mapped at the same address range in both.
Just don't use fork
. It's not the right tool for the job.