Question

I was wondering whether it would be legit to allocate a buffer for stdio stream buffering and use it with setvbuf (before fork), where the buffer is an anonymous mmap-"allocated" piece of memory shared between parent and child process?

Assuming the two are synchronized, am I allowed to assume that the outcome will be something sane, or should I rather avoid this at all costs?

Was it helpful?

Solution

You should not do this. Your C library will assume that the process has exclusive access to the standard IO buffer area, and will only mediate between threads of that process, no doubt using a mutex not in anonymous mmap. So you risk undefined behaviour if that buffer space is altered, just as if you wrote over it yourself.

However, a better question is why on earth would you want to do this? Why not make the buffer area /not/ shared (e.g. by using malloc() to allocate it), then everything will work fine.

OTHER TIPS

That depends on where your implementation of the C library stores the control information managing the buffer.

If all control information that is used to control concurrent writing from threads is stored within the buffer itself, everything might work fine.

However, if that control information is stored somewhere else, it will be duplicated between the processes. The libc instances in the two different processes will not realize when the other process has written to the buffer or flushed it, and chaos will ensue.

Even if your libc implementation does work fine with this setup, I would strongly advise against it. After all, the semantic of setvbuf() is to set a buffer, not storage for buffer control information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top