C program to display a busy symbol while processing

Hi

I was wondering how can a c program will be implemented which will display a symbol while calculating something.

for example : program should display some charters like /\/\ while calculating.

At least provide some pointers

thanks

Here's an extremely simple way:

#include <stdio.h>
#include <signal.h>

void showspin(void)     // Shows a different charcter every time its called
{
        static char *spin="-/|\\", pos=0;
        if(!spin[++pos]) pos=0; // If we hit the NULL terminator, skip to beginning of string
        // We have to use stderr, so it doesn't buffer, since we're not printing a newline
        fprintf(stderr,"%c\r",spin[pos]); // Show character at position 'pos' in string
}

void dospin(int sig)    // Starts showing spinner repeatedly
{
        showspin();
        signal(SIGALRM, dospin); // Register this function to be called on SIGALRM
        alarm(1); // Cause SIGALRM to happen 1 second later
}

void nospin()           // Cancels the spinner
{
        alarm(0);
        fprintf(stderr," \r"); // Erase the spinner
}

int main(void)
{
        int n;
        dospin(SIGALRM);
        for(n=1; n<(1000*1000*2000); n++);
        nospin();
}
1 Like

Hi Corona688, why the variable 'pos' needs to be a char data type? If I change it to int data type then the printing is not happening as expected, it stucks there in '/' char in the screen.

It doesn't.

I think you didn't make your int static; static locals act like globals, they only get initialized once and keep their values between different function calls. Without static, the variable would be brand-new every time, forgetting its value and starting over at zero.

1 Like

Yes Corona688, you're right :slight_smile: