Detection of Ctrl+C in M file
68 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Ilkay Meseli
il 30 Set 2014
Commentato: felipe masetti
il 30 Giu 2022
Hi everyone
I want to detect when somebody press "Ctrl C". How can I be detected it while an function is be running . if I do that , I will save some of variables to workspace.
0 Commenti
Risposta accettata
Geoff Hayes
il 30 Set 2014
Ilkay - you can try the following which is taken from Loren Shure's blog entry Keeping Things Tidy. It makes use of the onCleanup function which will perform "cleanup" tasks upon function completion or termination.
Suppose you have some function that does some work in a while or for loop which may take so long that the user becomes impatient and presses the ctrl+c to cancel out of the function. Within that function, we define a clean up function to fire when our main function/program terminates
function someFunction
% create our clean up object
cleanupObj = onCleanup(@cleanMeUp);
% load an image, create some variables
I = imread('someImage.jpg');
Z = zeros(42,24,42);
U = ones(1,2,3);
keepGoing = true;
while keepGoing
% do our work
% add a 100 msec pause
pause(0.01);
end
% fires when main function terminates
function cleanMeUp()
% saves data to file (or could save to workspace)
fprintf('saving variables to file...\n');
filename = [datestr(now,'yyyy-mm-dd_HHMMSS') '.mat'];
save(filename,'I','Z','U');
end
end
I tried the above on MATLAB R2014a (Mac OS X 10.8.5) and it would respond to the pressing of ctrl+c - firing the cleanMeUp function before terminating. Of course, that same function will fire if the program terminates regularly (i.e. if some exit condition is met and the code exits the while loop gracefully).
1 Commento
felipe masetti
il 30 Giu 2022
If your app is running on continuous loop and the work is not inside the while loop, bein triggered by events or timers for example, consider using "waitfor(keepGoing)", it will use less resources just to wait than the loop with pause.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Performance and Memory in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!