MATLAB Application Program Interface | Search  Help Desk |
mexAtExit | Examples See Also |
Register a function to be called when the MEX-file is cleared or when MATLAB terminates
#include "mex.h" int mexAtExit(void (*ExitFcn)(void));ExitFcn
mexAtExit
to register a C function to be called just before the MEX-file is cleared or MATLAB is terminated. mexAtExit
gives your MEX-file a chance to perform tasks such as freeing persistent memory and closing files. Typically, the named ExitFcn
performs tasks like closing streams or sockets.
Each MEX-file 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-file is locked, all attempts to clear the MEX-file will fail. Consequently, if a user attempts to clear a locked MEX-file, MATLAB does not call the ExitFcn
.
Consider a MEX-file named WrtFile
that calls mexAtExit
to register an exit function. The first time WrtFile
is called, WrtFile
invokes the ANSI fopen
routine to open a file named MyData
for writing. Each time WrtFile
is called, WrtFile
writes the first five values of the input vector to MyData
. When WrtFile
is cleared, MATLAB automatically invokes ExitFcn
, which calls fclose
to close the stream to MyData
.
FILE *fp; int first_time=1; /* Here is the exit function. */ void CloseStream(void) { mexPrintf("Closing MyData.\n"); fclose(fp); } void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { double *start; int c; /* Register an exit function. */ mexAtExit(CloseStream); /* If this is the first time that this MEX-file was called, open a write-only stream to file "MyData" */ if (first_time) { fp = fopen("MyData", "w"); if (fp == NULL) mexErrMsgTxt("Could not open MyData."); else mexPrintf("Opening MyData.\n"); mexAtExit(CloseStream); first_time = 0; } /* The user passes a vector in prhs[0]; write the first five elements of this vector to the data file. */ start = mxGetPr(prhs[0]); for (c=0; c<5; c++) fprintf(fp, "%.2g\t", *start++); fprintf(fp, "\n"); }Calling
WrtFile
three times writes three lines of data to MyData
.
>> WrtFile(1:5) Opening MyData. >> WrtFile([2 3 5 7 11]) >> WrtFile([3 5 7 9 11])Clearing
WrtFile
causes the exit function to be called.
>> clear WrtFile Closing MyData.The contents of
MyData
are
>> type MyData 1 2 3 4 5 2 3 5 7 11 3 5 7 9 11For an additional example, see
mexatexit.c
in the mex
subdirectory of the examples
directory.
mexLock
, mexUnlock