Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Behaviour because of sleep()

Tags:

c

I was just getting familiar with sleep(), i found that

#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
    printf("%d",i);
    sleep(1);
}
return 0;

}

this does not print number per iteration rather dumps all numbers when gets out of loop.... but when i modify printf...

#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
    printf("%d\n",i);
    sleep(1);
}
return 0;

}

and now as i've added '\n' new line it works as expected... why it is behaving strangely in former one...

like image 909
kHAzaDOOm Avatar asked Oct 24 '25 01:10

kHAzaDOOm


1 Answers

This is because the output buffer isn't being flushed (in other words, actually committed to the terminal). When you write a newline, the output buffer is more likely to be (but still not always, in some cases) flushed. Many terminal implementations do this to improve performance. To force the behaviour you want, you need to call fflush(stdout); after each printf call, like this:

#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
    printf("%d",i);
    fflush(stdout);
    sleep(1);
}
return 0;
}
like image 88
Delan Azabani Avatar answered Oct 25 '25 19:10

Delan Azabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!