0

The sleep() function doesn't seem to be respecting line by line compilation in c whenever I run something like this:

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

int main(){
  int i=0;

  while (i!=9){
    printf("sleep for 1 second");
    sleep(1);
    i++;
  }
  return 0;
}

The output ends up being "sleep for 1 second" printed out 10 times after waiting for 10 seconds, instead of the desired one of printing out "sleep for 1 second" every second for 10 seconds. Anyone know why this is and how to fix it?

VLL
  • 9,634
  • 1
  • 29
  • 54
  • Line buffering... try to add `\n` at the end of the printf call. – Lundin Dec 21 '21 at 08:54
  • @Lundin thank you! Worked perfectly, can you explain to me what line buffering is and how it relates to "flushing", not sure I understand why `printf()` has this behavior. Thanks! – Marc Robison Dec 21 '21 at 11:07
  • Did you check the duplicate link I posted? Basically C allows different forms of buffering, as show in the quote from the standard here: https://stackoverflow.com/questions/69724566/is-printf-buffering-part-of-the-c-standard – Lundin Dec 21 '21 at 11:10
  • @Lundin From what I understand, if I don't add `\n` to my `printf()` statement, my terminal will send everything to my screen at once in the end, in order to save time and that is called block buffering. Then if I add `\n` it will send out to my screen once it encounters that character and that is line buffering (which takes more time). Is that it? – Marc Robison Dec 21 '21 at 11:31
  • Yes that's correct. C requires all of stdout to get flushed before program exit. Alternatively to `\n` you can also call `fflush(stdout)`. – Lundin Dec 21 '21 at 11:32
  • Perfect, thanks for the help! – Marc Robison Dec 21 '21 at 11:37

0 Answers0