printf输出顺序错乱

11

我写了以下内容:

#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:

为什么会这样?

1个回答

12

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的函数中之外,还有其他方法吗? - Joel G Mathew
1
@Droidzone,你不能在函数外部放置可执行语句,例如函数调用。你需要将对 setbuf 的调用放在一个函数中,最好是在 main 函数的开头。 - dbush
使用 setvbuf(stdout, NULL, _IONBF, 0); 进行了工作。 - Joel G Mathew
@Droidzone 没错!已编辑。 - dbush
@Droidzone 注意它禁用缓冲,而不是在每个printf上调用fflush - phuclv
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接