Thursday 17 May 2012

Problems running gfortran compiled codes from MATLAB

A problem which had me stumped for a while was an apparent inability to run an executable compiled with gfortran from a MATLAB (v7.14) system() command (running on my 10.7.4 Mac). So, for trivial fortran code like:
program HelloWorld
write(*,*) 'hello world!'
end
compiled with gfortran (silently) returns no output when run from MATLAB with
>> [status, output] = system('./HelloWorld')
status =
     0
output =
     ''
After exploring the problem, I found out that the shell environment that MATLAB creates when system is called has a variable set called GFORTRAN_STDOUT_UNIT with a value of -1. This redirects stdout in gfortran to a file (usually fort.6), which is a fairly unhelpful, especially if you are doing something useful with stdout. Once you know this, you can work around it by unsetting the variable before doing anything else:
>> [status, output] = ...
       system('unset GFORTRAN_STDOUT_UNIT; ./HelloWorld')
status =
     0
output =
 Hello, world!
but it is a little clumsy. I have submitted a bug report to Mathworks, who have confirmed the behaviour and submitted it to the developer team. Also be aware that MATLAB monkeys about with other variables (for example, various directories are added to the beginning of your DYLD_LIBRARY_PATH, so if your executable relies on dylibs elsewhere there is the potential for collisions (for example, there is a version of one of the gfortran dylibs in one of paths added). You can also work around this, but it gets pretty ugly:
>> [status output] = ...
       system(['unset GFORTRAN_STDOUT_UNIT;...
               'export DYLD_LIBRARY_PATH=/usr/local/lib;', ...
               ' ./HelloWorld'])
You can find out what MATLAB has put in your environment by doing:
>> system('env')

No comments:

Post a Comment