为什么在写入 stderr 之前需要在 stdout 上使用 fflush? [英] Why would I need use fflush on stdout before writing to stderr?

查看:38
本文介绍了为什么在写入 stderr 之前需要在 stdout 上使用 fflush?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读UNIX 网络编程:套接字网络 API",在示例代码中,他们有一个错误处理函数,其中包含以下几行:

I am reading 'UNIX Network Programming: The Sockets Networking API' and in the example code they have an error handling function which contains the following lines:

fflush(stdout);     /* in case stdout and stderr are the same */
fputs(buf, stderr);
fflush(stderr);

其中 buf 包含错误描述.我不明白为什么在第一行的 stdout 上使用 fflush 以及为什么注释解释了使用它的原因.

Where buf contains the error description. I don't understand why fflush is used on stdout on the first line and why the comment explains the reason for its use.

推荐答案

这是因为缓冲.Stdout 和 stderr 通常以不同方式缓冲.标准输出通常是行缓冲的,这意味着它在看到换行符之前不会显示输出.Stderr通常是无缓冲的,会立即打印,你应该立即看到错误消息.

This is because of buffering. Stdout and stderr are usually buffered differently. Stdout is usually line buffered, meaning it will not display output until it sees a newline. Stderr is usually unbuffered and will print immediately, the thinking is you should see error messages pronto.

但他们都去同一个地方,终端.这就是 /* 在 stdout 和 stderr 相同的情况下的含义 */.他们通常是.但由于它们的缓冲方式不同,这可能会导致它们的显示顺序不正确.

But they both go to the same place, the terminal. This is what it means by /* in case stdout and stderr are the same */. They usually are. But because they're buffered differently this can lead to them being displayed out of order.

考虑这个代码.请注意缺少换行符.

Consider this code. Note the lack of a newlines.

#include <stdio.h>

int main() {
    fprintf(stdout, "This is to stdout. ");
    fprintf(stderr, "This is to stderr. ");
    fprintf(stdout, "This is also to stdout. ");
}

您希望输出为:

This is to stdout. This is to stderr. This is also to stdout.

但事实并非如此.出问题了.

But it isn't. It's out of order.

$ ./test
This is to stderr. This is to stdout. This is also to stdout.

stderr 的输出立即显示,它是无缓冲的.而 stdout 必须等到 stdout 缓冲区被换行符刷新.没有换行符,所以在程序退出时刷新.

The output to stderr is displayed immediately, it is unbuffered. While stdout has to wait until the stdout buffer is flushed by a newline. There is no newline, so it is flushed when the program exits.

通过在使用 stderr 之前刷新 stdout,您可以确保输出以正确的顺序出现,而不管缓冲如何.

By flushing stdout before you use stderr you ensure that the output comes in the right order regardless of buffering.

#include <stdio.h>
#include <unistd.h>

int main() {
    fprintf(stdout, "This is to stdout. ");
    fflush(stdout);
    fprintf(stderr, "This is to stderr. ");
    fprintf(stdout, "This is also to stdout. ");
}

$ ./test
This is to stdout. This is to stderr. This is also to stdout. 

这可确保错误消息与正常消息以正确的顺序出现.这样可以避免混淆哪些错误消息适用于程序的哪个部分.

This ensures that error messages come out in the right order along with normal messages. This avoids confusion about what error message applies to what part of the program.

这篇关于为什么在写入 stderr 之前需要在 stdout 上使用 fflush?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆