According to this StackOverflow question, printf
only flushes its output on a newline when the output device is interactive (e.g., a terminal). When the output device is non-interactive (e.g., a Python subprocess pipe, a file, etc.), stdout
is fully buffered, so the output will only be flushed when the buffer is full, when fflush(stdout)
is manually called, or when the buffer is otherwise forced to flush (e.g., on process exit).
Thus, readline
did not return because the application's stdout
was never flushed, so readline
had nothing to read. Changing the application code to this fixes the issue:
printf("Line 0
");
printf("Line 1
");
printf("Line 2
");
fflush(stdout); // New line
Others may wish to set the buffer mode of stdout
with setvbuf
rather than call fflush
.
I was surprised by this because the common understanding of printf
is that it flushes on a newline character, but this does not happen in all cases.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…