Sharing heap memory with fork()

前端 未结 5 1193
半阙折子戏
半阙折子戏 2021-02-15 11:53

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

5条回答
  •  我寻月下人不归
    2021-02-15 12:37

    Sorry for answering a month later, but I don't think the existing answers gave what the OP asked for.

    I think you are basically looking to do what is done by Redis (and propbably others). They describe it in http://redis.io/topics/persistence (search for "copy-on-write").

    • threads defeat the purpose
    • classic shared memory (shm, mapped memory) also defeats the purpose

    The primary benefit to using this method is avoidance of locking, which can be a pain to get right.

    As far as I understand it the idea of using COW is to:

    • fork when you want to write, not in advance
    • the child (re)writes the data to disk, then immediately exits
    • the parent keeps on doing its work, and detects (SIGCHLD) when the child exited. If while doing its work the parent ends up making changes to the hash, the kernel will execute a copy for the affected blocks (right terminology?).
      A "dirty flag" is used to track if a new fork is needed to execute a new write.

    Things to watch out for:

    • Make sure only one outstanding child
    • Transactional safety: write to a temp file first, then move it over so that you always have a complete copy, maybe keeping the previous around if the move is not atomic.
    • test if you will have issues with other resources that get duplicated (file descriptors, global destructors in c++)

    You may want to take gander at the redis code as well

提交回复
热议问题