【问题标题】:Why is the order of output of a C program different when its stdout is redirected to a file? [duplicate]为什么 C 程序的 stdout 重定向到文件时输出顺序不同? [复制]
【发布时间】:2017-05-17 05:13:29
【问题描述】:

这是我的程序。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello\n");
    system("uname");
    return 0;
}

这是输出。

$ gcc foo.c
$ ./a.out 
Hello
Linux

但是,如果我将程序的输出重定向到文件,我会看到输出的顺序是相反的,即 LinuxHello 之前打印。

$ ./a.out > out.txt
$ cat out.txt
Linux
Hello

为什么涉及重定向时输出的顺序不同?

【问题讨论】:

    标签: c linux output io-redirection


    【解决方案1】:

    这是因为标准输出以不同的方式缓冲。当您在没有重定向的情况下调用程序时,缓冲默认为逐行缓冲。在第二次调用中,缓冲区要大得多,并在程序终止时被写入。由于您之前终止了对 uname 的调用,因此此输出现在显示在文件的前面。当您依赖于排序时,您可以在 printf 调用之后显式调用 fflush(stdout),或者您可以通过 popen 调用 uname 并显式打印其输出。

    【讨论】:

      【解决方案2】:

      由于缓冲是在终端上完成的,所以输出的顺序可能会有所不同。

      【讨论】:

      • 错了。即使终端进行缓冲(我认为不是),它也只有一个“输入接收器”:数据的重新排序不能在那里发生。
      猜你喜欢
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2011-09-17
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2012-07-23
      相关资源
      最近更新 更多