zhang007z
zhang007z

Reputation: 115

I use sleep function in ubuntu ,but printf function run very slowly in while loop. why?

I use ubuntu 14.04 version system for below code. I use below code : (below code is infinite Loop)

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

int flag=0;

int main(void){

    printf("program start.\n");   
    printf("PID=%d\n",getpid());    
    printf("flag=%d\n",flag);
    //-----------I feel weired below do...while... sentences----------//
    do{
        printf("loop_");
        sleep(1);
       }while(flag==0);

    printf("program exit.\n");    
    return 0;
}

in the beginning below print result :

root@ubuntu:~/Desktop/my_test_code# ./issue 
program start.
PID=3113
flag=0
...........//start waiting here,and don't print "loop_"

then after I waited for long time this program prints a lot of "loop_". I find it very strange, and should print a string "loop_" and then, wait a second, then print a "loop_" again, and so on, why me waiting for a long time, do it start to print a lot of "loop_" ?

anybody has any idea for my issue . thank you in advance.

Upvotes: 1

Views: 186

Answers (2)

Jeegar Patel
Jeegar Patel

Reputation: 27230

Root cause:

Usually stdout's buffer are getting flushed by \n so here loop goes on and stdout did not get chance to buffered its data properly.

Solution:

There are three way here

1) Use \n at the end of printf

printf("loop_\n");

2) call fflush(stdout): after printf in loop.

3) Disabled the buffering for stdout stream using below call in your program

setvbuf(stdout, NULL, _IONBF, 0);

Upvotes: 0

Jarod42
Jarod42

Reputation: 217810

printf bufferizes its output (until a given size or \n), so you don't see the output until it flushes it.

changing your loop to

printf("loop_");
fflush(stdout);
sleep(1);

should solve your issue.

Upvotes: 5

Related Questions