Just set stdout to be line buffered at the beginning of your C program (before performing any output), like this:
#include <stdio.h>
setvbuf(stdout, NULL, _IOLBF, 0);
or
#include <stdio.h>
setlinebuf(stdout);
Either one will work on Linux, but setvbuf
is part of the C standard so it will work on more systems.
By default stdout will be block buffered for a pipe or file, or line buffered for a terminal. Since stdout is a pipe in this case, the default will be block buffered. If it is block buffered then the buffer will be flushed when it is full, or when you call fflush(stdout)
. If it is line buffered then it will be flushed automatically after each line.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…