簡體   English   中英

printf輸出亂序

[英]Output of printf out of order

我寫了以下內容:

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

為什么是這樣?

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都會立即出現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM