Translate

Thursday, June 13, 2013

Playing with the terminal buffer

.: Dealing with stdou and stderr :.

Hum ... so you've just wrote an awesome console app and it keeps joking with your face when it comes to writing its output to the screen.

Maybe the sample code bellow could help you a little.


 1 /* 
 2  * This program shows a simple stdout and stderr usage.
 3  *
 4  * Note that stdout uses a buffer and this can lead to undesired effects when 
 5  * printing, because it can occur while the buffer isn't empty. What a mess!
 6  * stderr doesn't use a buffer, so messages are print as they arrive.
 7  * 
 8  */
 9 
10 #include <stdio.h>
11 #include <stdlib.h>
12 
13 int main(int argc, char *argv[]) {
14 
15  int counter = 0;
16 
17  /* 
18   * Prints 5 dots without adjusting stdout buffer, one per second. 
19   * Note that it can happen (and probably will) of 5 points are printed 
20       * only once at the end of the program. stdout uses a buffer and 5 dots
21   * aren't enough to fill it! */
22  printf("\nTest 1/3. Using printf, no buffer adjustments. Wait 5 seconds\n");
23  while (counter++ <= 4) {
24   printf(".");
25   sleep(1);
26  }
27 
28  /* 
29   * Prints 5 dots, but this time adjusting the buffer, one per second.
30   * As we empty the buffer, its new content is processed immediately. 
31   */
32  counter = 0;
33  fflush(stdout);
34  printf("\nTest 2/3. Using printf, buffer adjustments. Note a dot per second.\n");
35  while (counter++ <= 4) {
36   fflush(stdout);
37   printf(".");
38   sleep(1);
39  }
40  
41  /* 
42   * Prints 5 dots using stderr, one per second.
43   * Note the lack of a buffer in stderr. Data is processed immediately. 
44   */
45  counter = 0;
46  fflush(stdout);
47  printf("\nTest 3/3. Using fprintf with stderr. Note a dot per second.\n");
48  while (counter++ <= 4) {
49   fprintf(stderr,".");
50   sleep(1);
51  }
52 
53 
54  return 0;
55 }

No comments:

Post a Comment