代码在while循环中睡觉期望输出

Reg*_*ser 3 c

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

我机器上面的输出是

hello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-err
Run Code Online (Sandbox Code Playgroud)

我不得不杀死程序来阻止它.这是正确和预期的行为.或者这是错误的.这是一个面试问题,因此我在这里发帖.

Oli*_*rth 8

这是预期的输出:

  • 由于循环,程序永远while (1)循环.
  • stdout是行缓冲的(默认情况下),因此只有在'\n'打印换行符()时才会刷新到控制台.由于您不打印任何换行符,因此您永远不会看到任何hello-out文字.
  • 但是stderr不是行缓冲(默认情况下),因此它会在每次新fprintf()调用时更新控制台.


Car*_*rum 5

stdout在大多数机器上缓冲.除非您打印换行符或呼叫fprintf,stdout否则您将看不到任何来电的输出fflush().

所以是的,这是预期的行为,大部分时间.