pic11
pic11

Reputation: 15003

Forking child process and C++ objects

I have several questions. Any input is appreciated. Thank you.

Upvotes: 2

Views: 1590

Answers (3)

Nemo
Nemo

Reputation: 71605

First of all, be aware that this behavior is extremely platform-dependent. If you are asking out of anything other than idle curiosity, may I suggest you re-think your design?

That said, what is and is not preserved by fork is specified by the POSIX standard. How to interpret this for C++ depends on how exactly your C++ (userspace) runtime is implemented.

File streams are an interesting case. The underlying file descriptor will get cloned, so both processes will have an open descriptor. But the user-space buffer (if there is one) will most likely get duplicated. So, for instance:

std::cout << "Hello!";
fork();
std::cout << std::endl;

...has a pretty good chance of printing Hello! twice, simply because the buffer will get copied (along with everything else in the address space of the process).

In short, I would answer your questions as:

  • It depends on the class and what you mean by "survive".

  • It is implemented by duplicating the entire virtual address space of the process, among other things.

  • Pointers keep their values, and what they point to gets duplicated. (This is done "lazily"; i.e. as "copy on write", so it is not as inefficient as it probably sounds)

  • (re: file streams) See above.

Upvotes: 6

Kerrek SB
Kerrek SB

Reputation: 477512

This can easily be answered by typing man fork:

  • "The child inherits copies of the parent's set of open file descriptors."

  • "The entire virtual address space of the parent is replicated in the child"

Basically, the child process will be in the exact same state as the parent (but see the man page for a long list of exceptions to this vastly oversimplified statement).

How is it implemented? What level of detail do you want? The memory might be implemented as copy-on-write. But that's not of your concern, the child process simply gets an exact copy of the entire memory.

Upvotes: 3

Michael Anderson
Michael Anderson

Reputation: 73590

Here's my understanding:

  • Do C++ classes survive forking?

yes.

  • If so, how it is implemented?

All of memory is copied so you have no trouble there.

  • What happens to pointers? Entire free store/heap is replicated and all virtual addresses are preserved?

yes.

  • What happens to file streams?

Both processes retain a copy of all open filestreams. (by default there are some fork options that can change this I think.) Streams opened after fork are not shared.

Upvotes: 7

Related Questions