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

一曲冷凌霜 提交于 2019-12-02 06:30:16
Charles Salvia

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?

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!