【问题标题】:Output of printf out of orderprintf的输出乱序
【发布时间】:2018-01-10 02:32:55
【问题描述】:

我写了以下内容:

#include <stdlib.h>
#include <stdio.h>
void ExecAsRoot (char* str);
int main ()
{
  printf ("Host real ip is:");
  ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
  return 0;
 }

void ExecAsRoot (char* str) {
  system (str);
}

我的预期输出是:

Host real ip is:7.17.11.29

而实际输出是:

7.17.11.29
Host real ip is:

这是为什么?

【问题讨论】:

    标签: c function printf


    【解决方案1】:

    printf 的输出正在被缓冲,因为正在打印的字符串不包含换行符。因此,缓冲区在程序结束之前不会被刷新,因此会出现在system 命令的输出之后。

    要刷新缓冲区,请使用fflush

    printf ("Host real ip is:");
    fflush(stdout);
    ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
    

    如果您希望对stdout 的所有写入都没有缓冲,您可以使用setvbuf 禁用缓冲:

    setvbuf(stdout, NULL, _IONBF, 0);     // _IONBF = unbuffered
    

    或者更简单地说:

    setbuf(stdout, NULL);
    

    然后所有对stdout 的写入都会立即出现。

    【讨论】:

    • 有没有办法隐含地“声明”我在每个 printf 上都需要 fflush?除了将其包装在包含 fflush 的函数中?
    • @Droidzone 您不能在函数之外拥有可执行语句,例如函数调用。你需要把对setbuf的调用放在一个函数中,最好是在main的开头。
    • setvbuf(stdout, NULL, _IONBF, 0);合作
    • @Droidzone 对!已编辑。
    • @Droidzone 注意它禁用缓冲,而不是它会在每个printf 上调用fflush
    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2019-02-26
    • 2019-01-25
    相关资源
    最近更新 更多