Why is the line following printf(), a call to sleep(), executed before anything is printed?

前端 未结 3 1879
陌清茗
陌清茗 2021-01-24 03:44

I thought I was doing something simple here, but C decided to go asynchronous on me. I\'m not sure what\'s going on. Here\'s my code:

#include 
in         


        
3条回答
  •  感情败类
    2021-01-24 04:06

    printf uses buffered output. This means that data first accumulates in a memory buffer before it is flushed to the output source, which in this case is stdout (which generally defaults to console output). Use fflush after your first printf statement to force it to flush the buffered data to the output source.

    #include 
    int main() {
        printf("start");
        fflush(stdout);
        sleep(5);
        printf("stop");
    }
    


    Also see Why does printf not flush after the call unless a newline is in the format string?

提交回复
热议问题