Unbuffered output in mixed C / Fortran programs

Georg Denk news_gd@gmx.de
Wed Oct 15 14:34:00 GMT 2008


Dear list,

I stumbled on a problem with unbuffered output, and I don't have any clue how to solve this. The
problem occurs in a mixed C / Fortran program in which I would like to have any output to
stdout being unbuffered (output to files should be kept buffered for performance reasons). It seems
that the output sequence depends if stdout is piped or not. If it is not piped, the output appears
in the sequence it was produced (by printf or WRITE). If, however, the output is piped,
all output produced by C comes first, followed by the Fortran output.

Here is a small example:

--- file main.c:
#include <stdio.h>

extern void fortran_output_(void);

int main(int argc, char **argv)
{
  /* we want unbuffered output to stdout: */
  setvbuf(stdout, 0, _IOLBF, 0);

  fortran_output_();

  printf("hello world, C (should be 2nd)\n");

  return 0;
}
--- end of main.c

--- file ftn.F
      SUBROUTINE FORTRAN_OUTPUT

      WRITE(*,*) 'HELLO WORLD, FORTRAN (should be 1st)'

      RETURN
      END
--- end of ftn.F

Compilation:
gcc -c -Wall main.c
gfortran -c -Wall ftn.F
gfortran -o buffer main.o ftn.o


start without pipe gives the expected output:
./buffer
 HELLO WORLD, FORTRAN (should be 1st)
hello world, C (should be 2nd)

start with pipe gives some un-expected output:
./buffer | more
hello world, C (should be 2nd)
 HELLO WORLD, FORTRAN (should be 1st)


I know about the environment variable GFORTRAN_UNBUFFERED_{ALL,PRECONNECT}, but this
is something my program can't control, as it has to be set by the users before starting the program.

Any hints how I could solve this issue?

Many thanks in advance,

Georg
  
-- 
Psssst! Schon vom neuen GMX MultiMessenger gehört? Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger



More information about the Fortran mailing list