c++forkownership-semantics

Ownership of global resources after fork


Consider a Foo that holds some resource

struct Foo
    {
    ~Foo();
    };

and a global std::vector<Foo>. Perhaps stupid example, but it illustrates the problem well.

std::vector<Foo> bar;

Now, the processes forks.

If bar is then only modified by the child process, then a call to exit should be the proper thing to do within the child process. If calling _exit, any Foo:s in bar would leak. If the parent added some stuff to bar before the fork, these object may be destroyed twice. Or maybe this is not a problem, because they should be considered as different objects.

What is the proper way of dealing with object lifetime together with a fork. Is the only sane way of dealing with this problems to let the child exec and start over?

I should notice that at this point in the program, there is guaranteed to be only one thread.


Solution

  • What is the proper way of dealing with object lifetime together with a fork?

    The proper way to handle shared resources when forking depends on what those objects or resources are.

    For any object or variable in the process memory, you automatically get a copy of it upon forking. Each process will then be able to modify or destroy any variable without affecting the other process. This also means that each process is responsible for cleaning up its unique copy of the resource.


    For other resources that exist outside the process, like a file, web socket, or shared memory; The best way to handle them will depend on what that resource is. Normally those best practices will be outlined by the library / API you are using to create those resources initially.