1

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.

0x0
  • 2,915
  • 5
  • 40
  • 67
  • 2
    Try flushing stdout after the printf. – Mat Sep 22 '16 at 12:35
  • Sure. It also seems to work if I use `fprintf(stderr,"i = %lu\n", i);`. But why would `clock_gettime` cause `i` to be buffered? `printf` seems to work fine without it. – 0x0 Sep 22 '16 at 12:40
  • 6
    clock_gettime is innocent, I'll wager your patience is the culprit. stdout is (usually) line-buffered when connected to a terminal, but "fully" buffered when connected to a file. You're probably not waiting long enough for the buffer to fill up and get flushed. stderr is (usually) not buffered. – Mat Sep 22 '16 at 12:46
  • Maybe your code run faster without `clock_gettime`, so buffering effect are not so visible? See http://stackoverflow.com/a/13933741/1212012 – Mathieu Sep 22 '16 at 12:46
  • Note: `diff = (((double)end.tv_sec + 1.0e-9*end.tv_nsec) - ((double)start.tv_sec + 1.0e-9*start.tv_nsec));` can lose precision. Does this cause your error failing `diff < 0.1`, IDK, Suggest `diff = (1.0*end.tv_sec - start.tv_sec) + 1.0e-9*(end.tv_nsec - start.tv_nsec);`. – chux - Reinstate Monica Sep 22 '16 at 12:53
  • Can you post the actual code you ran when you removed the call to `clock_gettime()`? Since that do-while loop is what's pacing the program, my bet is that it just streams the output out at a high rate, so that the system is forced to constantly flush the output buffer. – Mike Andrews Sep 22 '16 at 12:59

0 Answers0