简体   繁体   中英

text written to stdout doesn't appear until program completion

In this example, I am simply printing the numbers from 0 to 9 with a delay after each. However, instead of trickling the numbers to the output window, there is a long pause (with a "spinner" icon churning) and then all of the numbers are displayed at once (tested in both Chromium 44.0 and Firefox 40.0.3).

Is there a way to to make writes to stdout display immediately?

#include <stdio.h>

void time_waster( int reps=100 ) {
   static volatile unsigned counter=0;
   for ( int a=0; a<reps; a++ ) {
      for ( int b=0; b<1000*1000; b++ ) counter++;
   }
}

int main() {
  for ( int i=0; i<10; i++ ) {
     fprintf(stdout,"%d\n",i);
     fflush(stdout);
     time_waster();
  }
}

JavaScript and HTML built with:

emcc -Wall -Werror -o temp.html count.c

By the way, the combined size of the generated HTML+JavaScript for this small example is roughly 600KB (14619 lines), so debugging in the browser would be a non-trivial task.

Note: I had the same issue with std::cout in C++ (also with explicit flushing), but decided to write the question in C as a simplification of the problem.


I have discovered that the output is displayed as intended if I run the program with node.js :

node temp.js

So the problem only occurs when running in a browser using the HTML generated by the Emscripten compiler.

emscripten源我们发现fflush什么都不做。

Perhaps that behavior is by design, thus the main loop needs to be replaced by emscripten_set_main_loop or Emterpreter-Async.

https://github.com/kripken/emscripten/wiki/Emterpreter

#include <stdio.h>
#include <emscripten/emscripten.h>

void time_waster( int reps=100 ) {
   static volatile unsigned counter=0;
   for ( int a=0; a<reps; a++ ) {
      for ( int b=0; b<1000*1000; b++ ) counter++;
   }
}

int main() {
  for ( int i=0; i<10; i++ ) {
     fprintf(stdout,"%d\n",i);
     fflush(stdout);
     emscripten_sleep(0);
     time_waster();
  }
}

em++ -Wall -Werror -o temp.html count.cpp -s EMTERPRETIFY=1 -s EMTERPRETIFY_ASYNC=1 -s EMTERPRETIFY_WHITELIST="['_main']" -Oz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM