Borrar filtros
Borrar filtros

Detection of Ctrl+C in M file

82 visualizaciones (últimos 30 días)
Ilkay Meseli
Ilkay Meseli el 30 de Sept. de 2014
Comentada: felipe masetti el 30 de Jun. de 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.

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 30 de Sept. de 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 comentario
felipe masetti
felipe masetti el 30 de Jun. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by