Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

subsonix

macrumors 68040
Original poster
Feb 2, 2008
3,551
79
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?
 

ChrisA

macrumors G5
Jan 5, 2006
12,919
2,173
Redondo Beach, California
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?

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.
 

Gruffalo

macrumors newbie
Jan 27, 2006
13
0
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.
 

Sander

macrumors 6502a
Apr 24, 2008
521
67
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.
 

subsonix

macrumors 68040
Original poster
Feb 2, 2008
3,551
79
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.