1

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.

Trevor
  • 1,111
  • 2
  • 18
  • 30
zhang007z
  • 115
  • 7

2 Answers2

5

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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

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);
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222