Ctrl-C Detection in MATLAB MEX Files

Wotao Yin


MATLAB does not officially let your MEX file respond to Ctrl-C. While an m-file will terminate upon Ctrl-C is pressed, a MEX function won't. However, the undocumented function utIsInterruptPending (A few discussions such as this on Matlab Central have mentioned this function) can help a MEX function detect Ctrl-C and then run an exiting procedure.


Below I provide an example of capturing user input Ctrl-C in a MEX function [download].

The C++ source code MEX_CtrlC.cpp is: (you can also save it as a C file)

/* A demo of Ctrl-C detection in mex-file by Wotao Yin. Jan 29, 2010. */

#include "mex.h"

#if defined (_WIN32)
    #include <windows.h>
#elif defined (__linux__)
    #include <unistd.h>
#endif

#ifdef __cplusplus 
    extern "C" bool utIsInterruptPending();
#else
    extern bool utIsInterruptPending();
#endif

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int count = 0;    
    while(1) {
        #if defined(_WIN32)
            Sleep(1000);        /* Sleep one second */
        #elif defined(__linux__)
            usleep(1000*1000);  /* Sleep one second */
        #endif
                
        mexPrintf("Count = %d\n", count++);  /* print count and increase it by 1 */
        mexEvalString("drawnow;");           /* flush screen output */
        
        if (utIsInterruptPending()) {        /* check for a Ctrl-C event */
            mexPrintf("Ctrl-C Detected. END\n\n");
            return;
        }
        if (count == 10) {
            mexPrintf("Count Reached 10. END\n\n");
            return;
        }
    }
}

Compile

See here if libut.lib is not shipped with your MATLAB.

Results


>> MEX_CtrlC
Count = 0
Count = 1
Count = 2
Count = 3  (I pressed Ctrl-C right before this line appeared)
Ctrl-C Detected. END

>>

Explanation

utIsInterruptPending is an undocumented MATLAB API. It is implemented in libut.dll and included in the import library libut.lib. To use utIsInterruptPending in a mex-file, one must manually declare bool utIsInterruptPending() because this function is not included in any header files shipped with MATLAB (of course, as of 2010). Since libut.lib, by default, is not linked by mex, one must explicitly tell mex to use libut.lib.

The above MEX_CtrlC.cpp initiates count as 0 and starts a while loop. At each iteration, it calls a system function, Sleep on Windows or usleep on Linux, to pause for one second. Next, it displays the current count and then increases it by one. During the these two steps, if the user presses Ctrl-C, then utIsInterruptPending() returns true and triggers the exit message "Ctrl-C Detected. END." If no Ctrl-C is detected within 10 iterations, count == 10 triggers the other exit message "Count Reached 1. END."

Feedback

Hopefully, Mathworks will officially support the detection of Ctrl-C in a MEX file in a near future.

I would be delighted to hear from you if you find the trick useful, or if you have any suggestions, contributions, please contact me at
wotao dot yin @rice.edu. I will also appreciate your citing this page and helping spread this method.

Update

Ramon Casero Canas added a function to Gerardus that takes advantage of this feature. The function is called ctrlcCheckPoint(). See his original post.