Making interuptions in C using sleep()

Discussion in 'Mac Programming' started by subsonix, Jan 3, 2009.

  1. subsonix macrumors 68040

    Feb 2, 2008

    I have been trying to use the sleep function to get a short interuption in a C program, but is getting a bit of unexpected behaviour. If I for example type:

    #include <stdio.h>
    int main(int argc, char *argv[])
    	sleep (1);
    	return 0;
    I get a one second interuption before the printf. I have been trying to use it in a small for loop as well in a countdown function with a one second interuption between each step, but with the same result. All interuptions in the loop is performed first and then all other steps is printed in one go.

    Does anyone have any suggestion to why this might be?
  2. ChrisA macrumors G4

    Jan 5, 2006
    Redondo Beach, California
    Here is a guess

    What you may be seeing is the C library or OS buffering up the output. The program is working fine but the system can choose to keep any number of characters before they are actully printed.

    look up the "fsync" system call and also th "see also". Does Mac OS have an "fdatasync"?

    One more thing. "sleep" is not 100% accurate all the time.
  3. Gruffalo macrumors newbie


    Jan 27, 2006
    You might want to explicitly disable buffering for stdout. Try the following:
    setvbuf(stdout, (char*)NULL, _IONBF, 0L);
    prior to performing any I/O. See 'man setvbuf' for more details.
  4. Sander macrumors 6502

    Apr 24, 2008
    You can also use fflush(stdout) after the printf. It is indeed the buffering of the C I/O library which you're seeing here. Incidentally, most implementations implicitly flush when the output ends in a newline which is why you don't usually notice it.
  5. Muncher macrumors 65816


    Apr 19, 2007
    So then adding a newline character should fix it.
  6. subsonix thread starter macrumors 68040

    Feb 2, 2008
    Thanks for your suggestions. It was indeed the buffering of the output that caused this behaviour, interesting. I´ll look into the fsync and setvbuf man pages. I went with fflush(stdout) after printf which worked perfectly for this example.

    Muncher, in this case I´m using backspace instead of newline to erase the previous value and print the new one in the same place.

    Thanks again.

Share This Page