Register function to call when MEX-function clears or MATLAB terminates
Use mexAtExit to register a function to call just before clearing the MEX-function or terminating MATLAB®. mexAtExit gives your MEX-function a chance to perform tasks such as freeing persistent memory and closing files. Other typical tasks include closing streams or sockets.
Each MEX-function can register only one active exit function at a time. If you call mexAtExit more than once, MATLAB uses the ExitFcn from the more recent mexAtExit call as the exit function.
If a MEX-function is locked, you cannot clear the MEX-file. Consequently, if you attempt to clear a locked MEX-file, MATLAB does not call the ExitFcn.
In Fortran, declare the ExitFcn as external in the Fortran routine that calls mexAtExit if it is not within the scope of the file.