How to tell GDB to flush the stdio of the program being debugged

bufferdebugginggdbstdio

The stdio is usually buffered. When I hit a breakpoint and there's a printf before the breakpoint, the printed string may still be in the buffer and I can not see it.

I know I can flush the stdio by adding some flush code in the program.
Without doing this, is there any way to tell GDB to flush the stdio of the program being debugged after GDB stops? This way is more friendly when debugging a program.

Best Answer

Many recent UNIX stdio implementations will flush all buffers if you call fflush(NULL):

(gdb) call fflush(0)

If you don't have libc debug symbols installed, you may have to tell GDB about the type of fflush:

(gdb) call ((void(*)(int))fflush)(0)

But normally you shouldn't have to do that: if you called printf (and not fprintf), that goes stdout, which goes to your terminal, which would normally be line-buffered. So, so long as your printf printed a new line, the buffer would have been flushed after printf returned.