The following program increments the variable i
for 100ms
and prints the value. The problem is that it doesn't print anything onto file when redirecting the output from terminal.
#include <stdio.h>
#include <time.h>
struct timespec start={0,0}, end={0,0};
int main(void) {
double diff;
while(1) {
unsigned long i = 0;
clock_gettime(CLOCK_MONOTONIC, &start);
do {
++i;
clock_gettime(CLOCK_MONOTONIC, &end);
diff = (((double)end.tv_sec + 1.0e-9*end.tv_nsec) - ((double)start.tv_sec + 1.0e-9*start.tv_nsec));
} while(diff < 0.1);
printf("i = %lu\n", i);
}
return 0;
}
I compile it with gcc counter.c -o counter
and when I run ./counter
, the values of i
gets printed onto the screen, but when I do ./counter > file.out
, there is nothing in the file. I've also tried redirecting stderr 2>
and also ./counter > file.out 2>&1
. But if I remove the clock_gettime
function, it seems to work fine. Any idea why this happens and how to circumvent it?
Update:
My question is more about how is it printing to the screen (stdout
) immediately, but when redirected it is not immediate? Only using clock_gettime
seems to trigger this buffer. If not redirection works fine.