Search code examples
cforkmmapstdiosus

Is it legit to share the buffer used for stdio buffering between parent and child process?


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?


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.