c - 预测输出出错! - 使用 "fprintf & stdout"时这里发生了什么

标签 c stdout stderr

  #include <stdio.h>
  #include <unistd.h>
  int main()
  {
          while(1)
          {
                  fprintf(stdout,"hello-out");
                  fprintf(stderr,"hello-err");
                  sleep(1);
          }
          return 0;
  }

上面的程序打印了“hello-err”而不是“hello-out”,为什么?

最佳答案

你可以尝试使用

setbuf(stdout, NULL);

停止缓冲 stdout 否则你可以像这样刷新:

fprintf(stdout,"hello-out");
fflush(stdout);
fprintf (stderr, "hello-err");

来自 C 11 标准 §7.21.5.2 第 2 部分:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

关于c - 预测输出出错! - 使用 "fprintf & stdout"时这里发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32456493/

相关文章:

Python 'Logger' 类重复时间戳

command-line - 命令行 "usage"应该打印在 stdout 或 stderr 上吗?

c - 以独占模式打开锁定的文件

python - Subprocess.Popen() => 无输出

python - 使用 Paramiko 执行的命令不会产生任何输出

r - 如何在R中关闭管道连接之前从管道连接获取输出?

c - 从 opencv 中的两个网络摄像头流式传输错误

c - 调试!程序不会运行

c - 函数 'getline'的隐式声明,即使它是

java - 在 Java 中使用 System.err 有什么问题?