0

I am on a Windows 7 host with cygwin 1.7.0 installed.

I want to see the output of myTest.exe on the console and in the meanwhile have it written to myTest.log, but all output is shown only when myTest.exe is concluded.

I tried the solution suggested here and this works good. Then I wrote the following myTest.c:

#include <stdio.h>
#include <Windows.h>

int main() {
    printf ("hello\n");
    Sleep(5000);
    printf("goodbye\n");
    return 0;
}

and compile it with the command

gcc myTest.c -o myTest

Executing test.exe without tee works as expected, but if I execute

./myTest.exe | tee myTest.log

I get all output on the console only after myTest.exe is done.

Any suggestions how I can get the output to the console while myTest.exe is still running?

Community
  • 1
  • 1
S. Inder
  • 77
  • 1
  • 9

1 Answers1

0

The console output is buffered, so when the program exits, it flushes the buffer. You'll need to explicitly flush the buffer before the sleep so that it gets written immediately. For example:

fflush(stdout);
allen1
  • 714
  • 5
  • 13
  • Only when sending to an interactive session. When sending to a file or pipe, \n does not flush the buffer. http://stackoverflow.com/questions/5229096/does-printf-always-flush-the-buffer-on-encountering-a-newline – allen1 Jan 13 '16 at 18:19
  • No problem! I learn this way a LOT on Stack Overflow. It's one of the reasons I like coming here! :-) – allen1 Jan 13 '16 at 19:29
  • 1
    It works with `fflush(stdout)`. I solved it using `setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0)` (as suggested in the link that you posted) at the beginning of my main function, such that it's not necessary to use `fflush` the whole time ;) – S. Inder Jan 15 '16 at 10:53
  • Awesome! setvbuf is also a great way to get that behavior by default. Glad I could help! – allen1 Jan 15 '16 at 15:41