Linux fork within class on heap

十年热恋 提交于 2019-12-05 15:01:45

The child process is completely separate from the parent, and has a complete copy of the parent's variables. When the child executes (calls execve() or one of its relatives), no C++ destructors are executed. However, this has no effect whatsoever on the parent process.

So, there is no interference between the child and the process. It does not matter whether the parent waits for the child or not. As soon as the fork() returns (successfully) to the parent process, the child is running independently and nothing that the parent does to allocated variables will affect the child.

If you really try hard and have shared memory and variables allocated into shared memory via placement new and if the child goes cleaning variables up in shared memory before calling execvp(), or some other similarly far-fetched but not actually impossible scenario, then the child and parent are not completely independent. However, if you were doing something as complex as that, you probably would not be asking the question, either.

When you fork your process, you get an entire copy of the process (although typically it is implemented using copy-on-write), and by "entire copy", I mean an entire copy; including the various pages that have been allocated for that process, so logically there is a whole other copy of the heap and, for each thread, a copy of that thread and its associated stack, so yes, you have two copies of A and B.

A more pressing question, though, when it comes to forking is what happens to threads? Or what happens if you add an "atfork" hook for one of your threads? This one of the few ways that fork+exec can be fairly broken-ish or difficult to use within a UNIX context. It's usually a good idea to solve this once with a library or use popen, rather than trying to solve this multiple times all over the place.

A fork will copy the heap together with the rest of the process data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!