Making interuptions in C using sleep()

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

  1. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #1
    Hello,

    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:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
    	printf("3");
    	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

    Joined:
    Jan 5, 2006
    Location:
    Redondo Beach, California
    #2
    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

    Gruffalo

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

    Joined:
    Apr 24, 2008
    #4
    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

    Muncher

    Joined:
    Apr 19, 2007
    Location:
    California
    #5
    So then adding a newline character should fix it.
     
  6. subsonix thread starter macrumors 68040

    Joined:
    Feb 2, 2008
    #6
    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