Unexplored C-while Behavior

I am trying to run the following code:

#include <sys/time.h> #include <stdio.h> int main() { unsigned int ms, oldms = 0,dif; struct timeval tv; while(1) { gettimeofday(&tv, NULL); ms=tv.tv_sec; //printf("%d\n",ms-oldms ); dif=ms-oldms; if(dif>3) { printf("3 seconds up"); oldms=ms; } } } 

I expect it to print โ€œ3 seconds upโ€ every 3 seconds, but it does not display this message. I tried debugging it with gdb but nothing seems to be wrong and still doesn't output. While trying to debug, I added the printf statement, and the magic output can be seen.

If I run the program after deleting // printf ("% d \ n", ms-oldms); expression, there is no way out. I am not sure what is happening and whether it depends on anything.

$ gcc --version gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

+5
source share
2 answers

The reason is the reason for output buffering.

stdout by default binds to a string when connected to a terminal device. You can disable it using fflush(stdout); or using \n in printf() ie printf("3 seconds up\n"); . or disable it using setbuf(stdout, 0);

I / O is generally slow. Thus, the implementation uses a fixed-size buffer and printf after filling it. In practice, calling fflush(stdout); Too often can affect performance.

+10
source

published code has some problems

  • the oldms variable oldms not set to any specific value before the elapsed time is checked.
  • without calling fflush(stdout); or of a final new line ('\ n'), nothing will be output in the format line (for a very long time until the system stdout buffer is full)
  • for readability, the axiom only one statement per line and (at most) one variable declaration per statement applies to the code

the following code compiles and performs the desired operation

 #include <sys/time.h> #include <stdio.h> int main() { unsigned int ms; unsigned int oldms = 0; unsigned int dif; struct timeval tv; gettimeofday(&tv, NULL); oldms = tv.tv_sec; while(1) { gettimeofday(&tv, NULL); ms=tv.tv_sec; //printf("%d\n",ms-oldms ); dif=ms-oldms; if(dif>3) { printf("3 seconds up\n"); oldms=ms; } } } // end function: main 
+1
source

Source: https://habr.com/ru/post/1238380/


All Articles