Search code examples
cgcciostdoutdelay

How to pause between functions in a program in C with GCC?


So my problem is my program runs too fast that I can't see how it behaves. It's supposed to make the text crawl along the edges of the terminal. I tried to use sleep() to make a short pause betweenprintf(...)s so that it I can see where the text us going while it prints.

This is what it looks like:

https://i.sstatic.net/xZMLJ.gif

So I put sleep() function after the printfs so that it will pause before starting the loop again and make the text move slowly. But what happens is it pauses the programs indefinitely before it even starts. This also happens with usleep and system("pause 1"). This is what it looks like:

https://i.sstatic.net/KuquT.gif

==================================================================================

EDIT:

Okay, I figured it out on my own. It seems that sleep() only works if I put \n in my strings. I don't know why. I didn't even read this in the damn manuals.

So if you have

printf("HELLO\n");
sleep(3);
printf("HELLO\n");
sleep(3);
printf("HELLO\n");

It will result in:

HELLO

[pause for 3 seconds]

HELLO

[pause for 3 seconds]

HELLO

but if you remove the newline characters it will:

[pause for 9 seconds] HELLO HELLO HELLO

I don't know why this happens but it just does

================================================================================== EDIT:

This is how I wanted my program to work: https://i.sstatic.net/sWZ8E.gif

Thank you for your answers


Solution

  • Your observations do not due to sleep() not working, but to the fact that printf() uses stdout, which is line buffered. "line buffered" means, that what has been written to stdoutis buffered until the end of the line is reached before the buffer's content it is flushed out.

    So after the first printf("HELLO"); the output does not go to the screen but stays in the buffer, then sleep(1); is executed and makes you wait. Then for the next printf("HELLO"); the output still does not go to the screen, but the following sleep(1); again makes you wait for 1 second ... and so on until a line end if reached by your program printing a '\n' or by the program's end, which implicitly flushes the output buffer to the console.

    You can avoid the behaviour by flushing stdout's output buffer explicitly after every printf():

    #include <stdio.h>
    #include <unistd.h>
    
    int main(void)
    {
      printf("HELLO");
      fflush(stdout);
      sleep(3);
      printf("HELLO");
      fflush(stdout);
      sleep(3);
      printf("HELLO");
    /* fflush(stdout); */ /* not needed as buffers are implicitly flushed on the program's end */
    
      return 0;
    }