sleep() 一次执行,而不是在调用时执行

sleep() executes all at once rather then when it is called

我试着在 Linux 中做一个简单的测验,像这样:

#include <stdio.h>
#include <unistd.h>

void main()
{   
    printf("Simple arithmetic\n");
    printf("5 * 7 + 4 / 2 = ?\n");
    sleep(3);                       //wait for 3 seconds
    printf("And the answer is");
    for(int i = 5; i > 0; i--){ //wait for another 5 seconds printing a '.' each second
        sleep(1);
        printf(" .");
    }
    printf("\n%d!\n", 5*7+4/2);     //reveal the answer
}

问题是,这会输出前两个 printf,然后等待 8 秒左右,然后像这样打印其他所有内容:

>> Simple arithmetic
>> 5 * 7 + 4 / 2 = ?
>> // waits for 8 seconds instead of 3
>> And the answer is.....
>> 37! // prints everything out with no delay in-between

为什么会发生这种情况,我该如何解决?感谢您的帮助!

如果要立即输出,则需要flush。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void main()
{   
        printf("Simple arithmetic\n");
        printf("5 * 7 + 4 / 2 = ?\n");
        sleep(3);                       //wait for 3 seconds
        printf("And the answer is");
        for(int i = 5; i > 0; i--){  //wait for another 5 seconds printing a '.' each second
                sleep(1);
                printf(" .");
                fflush(stdout); // this line will do magic
        }
        printf("\n%d!\n", 5*7+4/2);     //reveal the answer
}