为什么是继该行的printf()调用睡眠(),任何事情之前执行打印? [英] Why is the line following printf(), a call to sleep(), executed before anything is printed?

查看:144
本文介绍了为什么是继该行的printf()调用睡眠(),任何事情之前执行打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我在这里做简单的东西,但C来决定去异步我。我不知道这是怎么回事。这里是我的code:

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 <stdio.h>
int main() {
    printf("start");
    sleep(5);
    printf("stop");
}

当我编译和运行,我注意到睡眠(5)就像一个魅力。但是编译器决定是跳过第一个的printf()和运行时,走出去的顺序,因此是一个好主意,程序等待5秒钟的然后的版画 startstop

When I compile and run, I notice that sleep(5) works like a charm. But the compiler decided it was a good idea to skip the first printf() and go out of order, so when running, the program waits for 5 seconds and then prints startstop.

这是怎么回事?我的理论是,该方案启动与外壳的打印操作,然后程序继续,留下猛砸等到程序不再忙于实际呈现的字符串。但我真的不知道。

What's the deal? My theory is that the program initiates the print operation with the shell, then continues with the program, leaving Bash to wait until the program is no longer busy to actually render the strings. But I really don't know.

感谢

推荐答案

的printf 使用 缓冲输出。这意味着数据先在内存缓冲区积累才刷新到输出源,在这种情况下,为标准输出(一般默认为控制台输出)。使用 fflush 后你的第一个的printf 语句,迫使它缓冲的数据刷新到输出源。

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");
}

结果

另请参阅<一个href=\"http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin\">Why除非换行符是格式字符串的printf确实没有呼叫后冲洗?

这篇关于为什么是继该行的printf()调用睡眠(),任何事情之前执行打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆