我的朋友给了我一个谜语。我跑了但没有得到预期的产出。 代码是:
#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语言中,指令逐行执行。但为什么不跟随这里?
答案 0 :(得分:3)
文件IO行为由系统决定,如果您想保留该顺序,则必须明确fflush
。请参阅以下计划:
while(i <= 5)
{
fprintf(stdout,"hello-out");
fflush(stdout);
fprintf(stderr,"hello-err");
fflush(stderr);
sleep(1);
i++;
}
答案 1 :(得分:2)
原因是输出缓冲。
默认情况下,stdout
被缓冲:如果它连接到终端,则它是行缓冲的,否则它是完全缓冲的。当它是行缓冲时,这意味着在打印换行符,填充缓冲区或显式刷新缓冲区之前不会打印任何内容。由于您没有打印换行符,因此在程序退出之前输出不会显示,因为此时刷新了所有stdio缓冲区。
stderr
默认情况下不缓冲。因此,任何写入它的内容都会立即出现。