C sleep method obstructs output to console

2019-08-31 05:06发布

问题:

I have a C program, where I just wanted to test if I could reproduce a console spinner used in npm install while it installs a module. This particular spinner simply spins in this order:

| / - \

on the same space, so I use the following program:

#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
        }
    }
}

So I found a way to make it rest for that long from <time.h> documentation and made this program:

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

But now nothing prints to the console. Does anyone know how I can go about producing the behavior I want?

EDIT According to what appears to be popular opinion, I've updated my code above to be the following:

#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
        }
    }
}

回答1:

You will need to flush after you wrote to the console. Otherwise, the program will buffer your output:

fflush(stdout);


回答2:

Things do get printed to console, it's just does not get flushed. Add fflush(stdout) to see the results, or set the console in an unbuffered mode by calling setbuf:

setbuf(stdout, NULL);

A bigger problem with your code is that your sleep method runs a busy loop, which burns CPU cycles for no good reason. A better alternative would be to call usleep, which takes the number of microseconds:

usleep(25000);


回答3:

The sleep function isn't really your problem. The issue is that the output is buffered. The simplest thing to do will be to research ncurses.

For now:

fflush(stdout);


标签: c printf sleep