在MATLAB中,我們可以在名爲me.m
的腳本中放置以下內容。從本身內部刪除一個MATLAB腳本是否安全?
delete('me.m');
在我們運行腳本後,它會自行刪除。在MATLAB中這樣的事情是安全的嗎?
在MATLAB中,我們可以在名爲me.m
的腳本中放置以下內容。從本身內部刪除一個MATLAB腳本是否安全?
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會不得不逐漸讀取腳本? –
@JoeC我很確定大多數腳本都適合Apple II的內存,但從理論角度來看,它可能最終會被分頁到磁盤。 – Suever
如果MATLAB腳本在解釋器中運行,我曾認爲解釋器可以通過解釋讀取腳本。上面的例子說解釋器已經接受了腳本的傳遞,釋放了文件鎖,並且會解釋一些中間代碼? –
我只是想說這是一個有趣的問題,暴露了許多人在使用MATLAB時不知道的事情之一。感謝問! +1 – Suever