8
#include <iostream>
#include <unistd.h>
#include <stdlib.h>

int main() {
    std::cout << 1;
    fork();
    exit(0);
}

The fork is located after streaming into cout, but this code prints 11. Why? And why does the code only print 1 if std::endl is added to cout?

#include <iostream>
#include <unistd.h>
#include <stdlib.h>

int main() {
    std::cout << 1 << std::endl;
    fork();
    exit(0);
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
COUNTERKILL
  • 173
  • 10
  • 8
    Buffers get flushed twice, in two processes. Man, that must be annoying. – Joker_vD Apr 08 '16 at 14:24
  • 1
    Unfortunately, C++ objects do not play well with forking. Basically, the object is effectively copy-constructed without copy-constructing it, and this circumvents a lot of protection built by C++. – SergeyA Apr 08 '16 at 14:31
  • I can only imagine the havoc a `fork()` would wreak on standard containers. Just don't do this. – Lightness Races in Orbit Apr 08 '16 at 14:48
  • The duplicate was presented to you while you were writing your question. Please pay attention! – Lightness Races in Orbit Apr 08 '16 at 14:51
  • That's how `fork()` works and it can be very useful behavior. It's vital to setting up pipes for IPC. I don't see how it would wreak havoc on standard containers. After the `fork()` you have 2 separate processes which have identical memory images in separate memory spaces. – Rob K Apr 08 '16 at 14:56

1 Answers1

12

It's caused by stream buffering. Inserting std::endl into the stream causes it to be flushed, so when you fork, the stream buffer is empty. When you don't insert std::endl, the stream doesn't get flushed until program exit. fork() causes the output stream to be duplicated, including unflushed contents. After the fork() there are 2 processes with unflushed output buffers containing the '1'. They each exit, flushing their buffers and you see "11".

Rob K
  • 8,757
  • 2
  • 32
  • 36