所以我知道printf()
是比write()
更高的水平,並最終使用write()
。 Printf()
被緩衝,write()
進行系統調用。爲什麼write()在輸出重定向的printf()之前打印?
實施例1,如果我是write()
之前printf()
運行一個程序然後它會的write()
值之前輸出的printf()
值。
示例2,如果我要運行相同的程序並使其通過輸出重定向到文件中,則在printf()
之前輸出write()
的值。
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("This is a printf test\n");
write(STDOUT_FILENO, "This is a write test\n", 21);
return 0;
}
我不明白這裏發生了什麼。在例1中,程序是否在運行前等待printf()
的輸出write()
?在示例2中,程序是否重定向了準備好的第一個輸出?並且因爲write()
是更低級別,並且不需要像printf()
那樣緩衝,那麼它首先被打印?
查找['setvbuf()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setvbuf.html)以及'_IONBF','_IOLBF'和'_IOFBF'的含義。當輸出到達終端時,你會得到'_IOLBF'行爲;當輸出到一個文件時,你會得到'_IOFBF'行爲。 – 2012-02-29 00:13:55