我创建了一个小的MATLAB-GUI来选择一个目录,并通过单击一个按钮在这个目录中启动一个外部MATLAB脚本。脚本的路径保存在一个变量file中,我用run(file)启动它。但是现在我想通过单击另一个按钮来停止这个脚本。有谁知道怎么做吗?
发布于 2016-09-16 00:01:28
如果不想对要调用的脚本进行任何更改,可以尝试在新的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从系统命令tasklist获取Matlab.exe的PID
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
endhttps://stackoverflow.com/questions/39512890
复制相似问题