Reputation: 99
I created a small MATLAB-GUI to choose a directory and to start an external MATLAB-script in this directory with a click on a button. The path to the script is saved in a variable file
and I start it with run(file)
. But now I want to stop this script by clicking on another button. Does anyone has an idea how to do this?
Upvotes: 2
Views: 250
Reputation: 51
If you don't want to make any changes in the scripts that you are calling, you could try to run the script in a new Matlab instance and then kill that matlab process when you want to stop the script running. Something like:
oldPids = GetNewMatlabPIDs({}); % get a list of all the matlab.exe that are running before you start the new one
% start a new matlab to run the selected script
system('"C:\Program Files\MATLAB\R2012a\bin\matlab.exe" -nodisplay -nosplash -nodesktop -minimize -r "run(''PATH AND NAME OF SCRIPT'');exit;"');
pause(0.1); % give the matlab process time to start
newPids = GetNewMatlabPIDs(oldPids); % get the PID for the new Matlab that started
if length(newPids)==1
disp(['new pid is: ' newPids{1}])
elseif length(newPids)==0
error('No new matlab started, or it finished really quickly.');
else
error('More than one new matlab started. Killing will be ambigious.');
end
pause(1);
% should check here that this pid is still running and is still
% a matlab.exe process.
system(['Taskkill /PID ' newPids{1} ' /F']);
Where GetNewMatlabPIDs
gets the PIDs for Matlab.exe from the system command tasklist
:
function newPids = GetNewMatlabPIDs(oldPids)
tasklist = lower(evalc('system(''tasklist'')'));
matlabIndices = strfind(tasklist, 'matlab.exe');
newPids = {};
for matlabIndex = matlabIndices
rightIndex = strfind(tasklist(matlabIndex:matlabIndex+100), 'console');
subString = tasklist(matlabIndex:matlabIndex+rightIndex);
pid = subString(subString>=48 & subString<=57);
pidCellFind = strfind(oldPids, pid);
pidCellIndex = find(not(cellfun('isempty', pidCellFind)));
if isempty(pidCellIndex)
newPids{end+1} = pid;
end
end
Upvotes: 1