2013-10-05 50 views
1

我的朋友給了我一個謎語。我運行它。但沒有獲得預期的產出。 代碼是:爲什麼打印到「stdout」不能順序執行?

#include <stdio.h> 
#include <unistd.h> 
int main() 
{ 
     while(1) 
     { 
       fprintf(stdout,"hello-out"); 
       fprintf(stderr,"hello-err"); 
       sleep(1); 
     } 
     return 0; 
} 

輸出不打印hello-out。 相反,它的打印像這樣無限:

hello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-err 

然後我試圖像這樣:

#include <stdio.h> 
#include <unistd.h> 
int main() 
{ 
    int i = 0; 

    while(i <= 5) 
    { 
      fprintf(stdout,"hello-out"); 
      fprintf(stderr,"hello-err"); 
      sleep(1); 
      i++; 
    } 
    return 0; 
} 

的optput是:

hello-errhello-errhello-errhello-errhello-errhello-errhello-outhello-outhello-outhello-outhello-outhello-out 

在C語言指令逐行執行線。但爲什麼它不在這裏?

+1

C程序有*兩*輸出流。它取決於你的平臺如何呈現這些。除非你努力分開記錄這兩個流,否則擔心這一點不會太令人滿意。 –

回答

3

文件IO行爲是由制度和確定的,如果你想保持這個順序,你必須明確地fflush。看到這個程序如下:

 while(i <= 5) 
    { 
      fprintf(stdout,"hello-out"); 
      fflush(stdout); 
      fprintf(stderr,"hello-err"); 
      fflush(stderr); 
      sleep(1); 
      i++; 
    } 
2

原因是輸出緩衝。

默認情況下,stdout緩衝:如果它連接到一個終端它的行緩衝,否則它的全緩衝。當它是行緩衝時,這意味着只有在打印換行符,緩衝區填滿或緩衝區被明確刷新之前,纔會打印任何內容。由於您不打印換行符,因此在程序退出之前輸出不會顯示,因爲當時所有stdio緩衝區都將被刷新。

stderr,在另一方面,默認情況下不進行緩衝。所以寫入它的東西立即出現。

+0

感謝您對stdout信息的緩衝。非常清楚。 –