【问题标题】:Why is the line following printf(), a call to sleep(), executed before anything is printed?为什么 printf() 之后的行(对 sleep() 的调用)在打印任何内容之前执行?
【发布时间】:2013-04-24 02:51:11
【问题描述】:

我以为我在这里做一些简单的事情,但 C 决定对我进行异步处理。我不确定发生了什么事。这是我的代码:

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

当我编译和运行时,我注意到sleep(5) 就像一个魅力。但编译器认为跳过第一个 printf() 并出现故障是个好主意,因此在运行时,程序等待 5 秒然后打印 startstop

有什么关系?我的理论是程序使用 shell 启动打印操作,然后继续执行程序,让 Bash 等到程序不再忙于实际呈现字符串。但我真的不知道。

谢谢

【问题讨论】:

标签: c printf sleep


【解决方案1】:

printf 使用缓冲输出。这意味着数据在刷新到输出源之前首先在内存缓冲区中累积,在这种情况下为stdout(通常默认为控制台输出)。在您的第一个 printf 语句之后使用 fflush 强制它将缓冲的数据刷新到输出源。

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


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

【讨论】:

  • 谢谢!我应该知道会有更多。起初我以为我安装了一个恶意 Python 安装程序,它嫉妒这个 C 程序在语法简洁方面与它的实现相媲美。
【解决方案2】:

尝试在您的 printf 语句中添加 '\n',如下所示:

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

编译器没有乱序执行。只是输出被累积,然后在程序退出时显示。 '\n' 将调用 tty 驱动程序中的行规则来刷新输出。

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2020-07-09
    • 2013-06-27
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多