2

I have a Matlab code that runs a system script. The script may be stopped due to the command runs. I want to know if there is a way that the program knows if it has taken a long time and do something else. Here is the code:

tic;
[status,cmdout]=system(iperfcmd); % The program can be blocked here
toc; % I want to know if it has taken a long time (like 5 seconds) for the system call and kill it. 
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Masoud
  • 305
  • 1
  • 12

2 Answers2

2

How about performing the system call asynchronously (https://uk.mathworks.com/help/parallel-computing/parallel.pool.parfeval.html) and polling from the main thread, something like this:

% Setup
tMax = 5;         % Maximum time to wait for system call
pollDelay = 1;    % Time between polls
timeOut = false;
% Run system call asynchronously
F = parfeval(@timeSystem,3,'iperfcmd');
tic
% Poll at regular intervals, break out if it finishes or exceeds time limit 
while strcmp(F.State,'running') && ~timeOut
    t = toc;
    pause(pollDelay)
    if t>tMax 
        timeOut = true; % This terminates the loop (alternatively use break)
    end
end

if strcmp(F.State,'finished')
    [status,cmdout,runTime]=fetchOutputs(F);
else
    % Handle hanging system call here
    cancel(F) % Cancelling the FutureEvent might terminate the system call?
end

function [status,cmdout,runTime] = timeSystem(command)
tStart = tic;
[status,cmdout] = system(command)
runTime = toc;
end

Hopefully that works for you. It's untested tested due to not having iperfcmd

B. Thomas
  • 192
  • 9
  • I want to know the exact time of execution (returning from the system call) of `iperfcmd`. I used `afterEach` function like this: `F = parfeval(@system,2,iperfcmd); tic; delayFuture = afterEach(F,@toc,1);` but it gives me error "Error using toc, too many arguments". How can I use `toc` in `afterEach` function? – Masoud Feb 11 '20 at 23:10
  • Then I would suggest then placing the tic/toc around the system call in a new function. I'll edit the code in the answer. – B. Thomas Feb 12 '20 at 11:23
0

Assign toc to a variable and then do logic on that value

tic
[status,cmdout]=system(iperfcmd);
elapsedTime = toc;

elapsedTime > 5
Mimakari
  • 411
  • 3
  • 12
  • I know that I can do the logic on elapsedTime. But the problem is when the program is stuck in performing the system command, it does not do anything else. So the program cannot check elapsedTime without being done with system(iperfcmd). I need a workaround for this. – Masoud Feb 06 '20 at 19:43
  • @Masoud sorry, I'm afraid I misinterpreted the question – Mimakari Feb 07 '20 at 13:39