1

Recently I learned that we can use onCleanup to release sources

My code also uses timer

However the two things do not work together.

 function runMe
    f = fopen('log','w');
    fprintf(f, 'exit');
    fclose(f);
 end
 c = onCleanup(@() runMe());
 t = timer;
 t.TimerFcn = @(~,~) exit();
 t.StartDelay = 10;
 start(t);

When time is out, the 'log' file is not generated. If I use the 'exit' command, runMe is called. finish.m works at this case.

Is this expected? Or maybe I did not use them correctly.

Community
  • 1
  • 1
Joe C
  • 2,629
  • 1
  • 22
  • 43
  • It works just fine for me. It may be worth specifying a *full* file path to the log file so there is no ambiguity of where it's writing to – Suever Dec 04 '16 at 22:01
  • @Suever Using full path does not help. I use log write as an example to show the issue. I found the problem in my owner code base, and some code in onCleanup does not run when time is out. But that code is too much to show, so I use this log write. I use 16a. Which version of MATLAB do you use? – Joe C Dec 04 '16 at 22:08
  • Very interesting. It worked just fine in 2014a but doesn't in 16a. It seems like 16a doesn't clear the workspace on exit. Have you tried the `finish.m` approach instead? – Suever Dec 04 '16 at 22:13
  • @Suever I did not try finish.m. I had thought that MATLAB can find only the first finish.m in the code path. If users have an existing finish.m, then mine would overwrite theirs. I did not figure out how it works. So I tried onCleanup. – Joe C Dec 04 '16 at 22:22
  • Sure there are some downsides to `finish.m` but you could at least test it to see if you have the same issue – Suever Dec 04 '16 at 22:26
  • 1
    So based on [the documentation](https://www.mathworks.com/help/matlab/matlab_prog/cleaning-up-when-the-function-completes.html#bsns2hs-1) it seems like `onCleanup` running on exit isn't exactly documented behavior so maybe that behavior has changed from version to version. – Suever Dec 04 '16 at 22:31
  • @Suever Okay. Maybe I should not rely on onCleanup to release resource as discussed here (http://stackoverflow.com/questions/40937292/how-to-release-resources-if-a-program-crashes). And maybe onCleanup is designed for only RAII-like things. – Joe C Dec 04 '16 at 22:47
  • 1
    You're running into the issues described in http://stackoverflow.com/questions/22898001/matlab-oncleanup-function-not-executed, and I think the solution should be essentially the same. – Sam Roberts Dec 05 '16 at 11:56

0 Answers0