On Mon, Oct 23, 2023 at 09:31:11AM -0400, Greg Wooledge wrote:
> On Mon, Oct 23, 2023 at 11:15:22AM +0200, Thomas Schmitt wrote:
> > it helps to do
> >   fflush((stdout);
> > after each printf(), or to run before the loop:
> >   setvbuf(stdout, NULL, _IONBF, 0);
> > 
> > So it is obvious that the usual output buffering of printf() causes the
> > repetitions of text.
> 
> Yes, it looks like a buffering issue to me as well.  Or, more generally,
> some kind of weird interaction between buffered stdio FILEs and the
> underlying Unix file descriptors, when new processes are being fork()ed.

More specifically, fork() does not play nicely with stdio buffering.

For performance reasons, stdio tends to read and write in chunks, reducing
the number of read() and write() calls.  Some data is stored in the stdio
buffers, and that data is getting copied to both processes in the fork()
call.

If you want to mix fork() and stdio, be sure to flush buffers before the
call to fork.  Depending on the task, it may be easier to use the underlying
read() and write() calls.

Jon Leonard 

Reply via email to