[英]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.