When the program is run from the terminal, the output is as expected: a single line containing "foobar". However, when the output is sent to a pipe or redirected to a file, two lines appear in the output. (Actually, the problem was a bit more complicated: there were
if(fork() == 0)
n fork()calls and there were exactly
nadditional copies of the output). After a bit of digging around and not finding any obvious fault, I asked about it on IRC.
It turned out that
stdoutis fully buffered when it is attached to a pipe or a file. What happened is that
fork()duplicated also the internal I/O buffers, which got flushed after the child process exited, thus producing extra output. I solved the problem by inserting a
fflush(NULL);statement before forking, which flushes buffers of all output streams.