C sleep方法阻碍输出到控制台

时间:2015-02-05 18:16:43

标签: c printf sleep

我有一个C程序,我只想测试是否可以在安装模块时重现npm install中使用的控制台微调器。这个特殊的微调器按此顺序旋转:

| / - \

在同一个空间,所以我使用以下程序:

#include <stdio.h>

int main() {
    char sequence[4] = "|/-\\";

    while(1) {
        for(int i = 0; i < 4; i++) {
            // \b is to make the character print to the same space
            printf("\b%c", sequence[i]);
            // now I want to delay here ~0.25s
        }
    }
}

所以我找到了一种方法让它在<time.h> documentation长时间休息并制作了这个程序:

#include <stdio.h>
#include <time.h>

void sleep(double seconds) {
    clock_t then;

    then = clock();

    while(((double)(clock() - then) / CLOCKS_PER_SEC) < seconds); //do nothing
}

int main() {
    char sequence[4] = "|/-\\";

    while(1) {
        for(int i = 0; i < 4; i++) {
            printf("\b%c", sequence[i]);
            sleep(0.25);
        }
    }
}

但现在没有任何东西打印到控制台。有谁知道如何制作我想要的行为?

编辑根据看似流行的观点,我已将上面的代码更新为以下内容:

#include <stdio.h>
#include <unistd.h>

int main() {
    char sequence[4] = "|/-\\";

    while(1) {
        for(int i = 0; i < 4; i++) {
            printf("\b%c", sequence[i]);
            /* fflush(stdout); */
            // commented out to show same behavior as program above
            usleep(250000); // 250000 microseconds = 0.25 seconds
        }
    }
}

3 个答案:

答案 0 :(得分:2)

写入控制台后需要刷新。否则,程序将缓冲输出:

fflush(stdout);

答案 1 :(得分:1)

事情确实打印到控制台,它只是没有被刷新。添加fflush(stdout)以查看结果,或通过调用setbuf将控制台设置为无缓冲模式:

setbuf(stdout, NULL);

代码的一个更大的问题是你的sleep方法运行一个繁忙的循环,它没有充分的理由燃烧CPU周期。一个更好的选择是调用usleep,它需要微秒数:

usleep(25000);

答案 2 :(得分:1)

睡眠功能不是你的问题。问题是输出是缓冲的。最简单的方法是研究ncurses。

目前:

fflush(stdout);