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

前端 未结 3 1872
陌清茗
陌清茗 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 <stdio.h>
    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?

    0 讨论(0)
  • 2021-01-24 04:17

    Try adding '\n' to your printf statements, like so:

    #include <stdio.h>
    int main() {
        printf("start\n");
        sleep(5);
        printf("stop\n");
    }
    

    The compiler is not executing this out of order. Just the output is getting accumulated, and then displayed when the program exits. The '\n' will invoke the line discipline in the tty drivers to flush the output.

    0 讨论(0)
  • 2021-01-24 04:17

    Read this Q&A, it explains it.

    0 讨论(0)
提交回复
热议问题