matlab - 从自身内部删除 MATLAB 脚本是否安全?

标签 matlab

在 MATLAB 中,我们可以将以下内容放在名为 me.m 的脚本中。

delete('me.m');

在我们运行脚本后,它会自行删除。这样的事情在 MATLAB 中安全吗?

最佳答案

脚本在调用时由MATLAB编译,编译后的脚本加载到内存中,然后从内存中运行。这适用于类、函数、脚本和 MEX 文件。您可以使用 inmem获取当前存储在内存中的所有源文件的列表。

如果您从脚本中删除源文件,它仍会完成(因为它使用的是内存版本),但显然无法再次运行。

您可以通过将其粘贴到脚本中来亲自查看

%// Prove that we started
disp('About to self destruct')

%// Get the name of the current script
this = mfilename;

%// Remove the source file
delete(which(this))

%// Make sure we actually removed it
if exist(which(this))
    disp('Not deleted')
else
    disp('File is gone!')
end

%// Check that it is still in memory
if any(ismember(this, inmem))
    disp('Still in memory')
else
    disp('Not found in memory')
end

%// Demonstrate that we still execute this
disp('I am unstoppable')

如果您随后尝试再次运行此脚本,将找不到它。

关于存储在内存中的函数、脚本等。您始终可以使用 clear 显式清除它们或清除 specific type 的所有内容来自内存。

%// Clear out an explicit script
clear scriptname

%// Clear all functions & scripts
clear functions

有趣的是,即使您从脚本 scriptname.m 中调用 clear scriptname,也不会阻止脚本完成。

%// Get the name of the script
this = mfilename;

%// Delete the file
delete(which(this));

%// Try to clear this script from memory
clear(this);

%// Prove that we're still running
disp('Still here')

另一个有趣的花絮是 mlock旨在防止当前正在执行的函数/脚本即使在完成后也不会从内存中删除。如果将其插入脚本(删除文件后),脚本使用inmem 脚本完成后显示,但是,您由于找不到源文件,仍然无法再次调用脚本。

this = mfilename;
delete(which(this));
mlock
disp('Still here')

然后从命令窗口

%// Run the self-destructing script
scriptname

%// Check to see if it is in memory
ismember('scriptname', inmem)

%// Now try to run it again (will not work)
scriptname

总结

那么从自身内部删除脚本安全吗? 。似乎您无法通过删除源文件来阻止当前正在执行的脚本运行完成。

关于matlab - 从自身内部删除 MATLAB 脚本是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626303/

相关文章:

matlab - 如何使用两个单字段 Matlab 结构执行联合

image - 如何将 Gabor 小波应用于图像?

c# - 作为 C# 安装程序向导的一部分安装 Matlab MCR

matlab - 如何在 MATLAB 绘图中标记一个点?

matlab - 如何在不使用临时变量的情况下从函数中获取第二个返回值?

添加字幕后,Matlab 图无法再平移或缩放

python - 用于 Python 图像处理的类似 Blockproc 的函数

performance - MATLAB 中加速 exp(A*x) 的解析方法

matlab - 有比这更好的矢量化技术吗?

arrays - 如何在 Matlab 中比较多维数组?