2

我创建了一个小的 MATLAB-GUI 来选择一个目录并通过单击一个按钮在该目录中启动一个外部 MATLAB 脚本。脚本的路径保存在一个变量中file,我以run(file). 但现在我想通过单击另一个按钮来停止这个脚本。有谁知道如何做到这一点?

4

1 回答 1

1

如果您不想对正在调用的脚本进行任何更改,您可以尝试在新的 Matlab 实例中运行该脚本,然后在您想停止该脚本运行时终止该 matlab 进程。就像是:

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']);

GetNewMatlabPIDs从系统命令获取 Matlab.exe 的 PID 的位置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
于 2016-09-15T16:01:27.837 回答