Reputation: 305
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.
Upvotes: 2
Views: 406
Reputation: 192
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
Upvotes: 2
Reputation: 449
Assign toc
to a variable and then do logic on that value
tic
[status,cmdout]=system(iperfcmd);
elapsedTime = toc;
elapsedTime > 5
Upvotes: 0