为什么 fprintf(outputFile,"") 在 gdb 内部不起作用?

Why doesn't fprintf(outputFile,"") work from inside gdb?

当我尝试从 gdb 内部调试一段代码时,控件到达输出文件的 fprintf 语句时,它没有在文件中生动地显示输出,它只是显示为空,尽管工作正常只需从终端输入一个简单的 运行 程序就可以了。

从 gdb 内部调试时,如何在 outputFile 上激活输出?

注意:我并不是在谈论 gdb,我只是在问如何在从 gdb 调试时动态地在文件中获取输出。

这可能是由于 stream buffering:

Characters that are written to a stream are normally accumulated and transmitted asynchronously to the file in a block, instead of appearing as soon as they are output by the application program. Similarly, streams often retrieve input from the host environment in blocks rather than on a character-by-character basis. This is called buffering.

试试这个例子:

#include <stdio.h>

int main(void) {
    FILE *f = fopen("foo.txt", "w");
    printf("Break here and go line by line.");
    fprintf(f, "Bar\n");
    printf("Nothing in foo.txt yet.");
    fflush(f);
    printf("Buffer has been written to foo.txt now.");
    fprintf(f, "Baz\n");
    printf("Baz is still only in the buffer.");
    fclose(f);
    printf("The buffer was written to the file before closing.");
}

How do I get my output lively on the outputFile when debugging from inside gdb?

这样做:

(gdb) call fflush(0)

这将导致正在调试的程序刷新其所有输出流。