cbashprocessoutput-redirect

Initial output of parent is lost while redirecting


The program I was trying to write was supposed to define some constants (C macro/constants). So I wrote two C programs:

  1. hashgen : This generates constants from the input file.
  2. loopy : This executes the hashgen with some file names.

Here is how I execute loopy:

./loopy *.txt >> constants.h

The loopy code snippet is below

int main(int argc, char** argv) {
    char buf[256];
    puts("#ifndef CONSTS_DEFINED\n#define CONSTS_DEFINED");
    while(--argc > 0) {
         sprintf(buf, "./hashgen %s", argv[argc]);
         system(buf);
    }
    puts("#endif");
    return 0;
}

After executing the above script, the #ifndef .... lines are missing while #endif line is present. Why the children are overwriting the parent's output?

I agree that there are better ways to this, but there was a need for this at that moment. Now I want to know why this is happening. :)


Solution

  • The output from puts doesn't go directly to the file, but to an internal buffer. So when the external program is called, nothing has yet been output. The program outputs its things, and then the main program continues, and when it finishes, its stdio buffer is flushed, and your directives end up at the end. This appears with ordinary redirection too, not only appending.

    A solution is to use fflush(stdout) before calling external programs which do I/O.