0

I have been playing around with the code below on both WSL and Windows. The code works as expected on Windows after compiling with MSVC. On WSL2(Ubuntu) I get unexpected results after compiling with GCC.

The code generates 2 random integers and print them, then waits 5 seconds before program exits. But on bash the print only happens after the 5 seconds, not before.

Please have a look at the code below.

Thanks

#include <stdio.h>
#include <time.h>
#include <stdlib.h>



int main(){


    clock_t start_time = clock();


    srand(time(NULL));
    for(unsigned int i = 0; i < 2; i++)
            printf("%u ", rand() % 10);         // <--- Prints after 5 seconds on WSL 2 (Ubuntu)


    while(clock() - start_time < CLOCKS_PER_SEC * 5);


    return 0;
}
Nic
  • 49
  • 6
  • 2
    Note that you don't actually wait between te prints, they both happen immediately, then you wait, because the waiting is outside the for loop. Your other problem would likely be due to (line) buffering. If having them on seperate lines (`"%u\n"`) changes things (if you have the delay between them), then that's it. If you want to keep them on the same line, you need to flush the buffer for `stdout`. – Thomas Jager May 08 '20 at 15:16
  • 4
    Generally, if you want a `printf` call to appear immediately, you should flush the output buffer by calling `fflush( stdout );`. – Andreas Wenzel May 08 '20 at 15:19
  • Tnanks guys, flushing the buffers solved things – Nic May 08 '20 at 15:27
  • 2
    Related question: [Why does printf not flush after the call unless a newline is in the format string?](https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin/) – Andreas Wenzel May 08 '20 at 15:30

0 Answers0