Matlab Gfortran stream redirect

Matlab redirects the I/O streams of binaries compiled with GFortran by setting runtime environment variables for stdout, stderr, and stdin. This can lead to unexpected behavior of programs run from Matlab with built-in functions like system() as well as external language interfaces run from Matlab scripts like Java ProcessBuilder, Python subprocess, etc.

Disable I/O stream capture before the external process is started in the Matlab script:

outold = getenv("GFORTRAN_STDOUT_UNIT");
setenv("GFORTRAN_STDOUT_UNIT", "6");

errold = getenv("GFORTRAN_STDERR_UNIT");
setenv("GFORTRAN_STDERR_UNIT", "0");

inold = getenv("GFORTRAN_STDIN_UNIT");
setenv("GFORTRAN_STDIN_UNIT", "5");

After the process is finished, restore the original values:

setenv("GFORTRAN_STDOUT_UNIT", outold);
setenv("GFORTRAN_STDERR_UNIT", errold);
setenv("GFORTRAN_STDIN_UNIT", inold);

Runtime environment variables affect GCC programs including C and C++ programs.