2

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.

4

2 回答 2

1

与 a 一起处理对象生命周期的正确方法是fork什么?

分叉时处理共享资源的正确方法取决于这些对象或资源是什么。

对于进程内存中的任何对象或变量,您在分叉时会自动获得它的副本。然后每个进程将能够修改或销毁任何变量而不影响其他进程。这也意味着每个进程都负责清理其唯一的资源副本。


对于存在于进程之外的其他资源,例如文件、Web 套接字或共享内存;处理它们的最佳方法将取决于该资源是什么。通常,您最初用于创建这些资源的库/API 将概述这些最佳实践。

于 2019-10-16T16:59:36.003 回答
0

一旦你fork编辑了,你的变量就会表现出写时复制语义,因此子进程的任何更改都会导致子进程的唯一变量不与父进程共享。类似地,父进程中的更改将导致子进程具有新副本并且不会传播,因此父进程可以在exit不中断子进程的情况下进行。我这样做是为了实现一个自我更新程序。

请注意,如其他答案所述,“全局资源”应根据具体情况进行处理,但变量不是全局资源。

于 2019-10-16T17:09:54.767 回答