अंत में मैंने लगातार दो परीक्षणों (movefile, और स्थानांतरित फ़ाइल की सामग्री को सत्यापित करने के आधार पर एक कार्यान्वयन किया)।
बहुत अच्छी तरह से लिखा नहीं है, लेकिन यह मेरे लिए अभी काम करता है।
+++++ file_lock.m ++++++++++++++++++++++++
function file_lock(op, filename)
%this will block until it creates the lock file:
%file_lock('create', 'mylockfile')
%
%this will remove the lock file:
%file_lock('remove', 'mylockfile')
% todo: verify that there are no bugs
filename = [filename '.mat'];
if isequal(op, 'create')
id = [tempname() '.mat']
while true
save(id, 'id');
success = fileattrib(id, '-w');
if success == 0; error('fileattrib'); end
while true
if exist(filename, 'file'); %first test
fprintf('file lock exists(1). waiting...\n');
pause(1);
continue;
end
status = movefile(id, filename); %second test
if status == 1; break; end
fprintf('file lock exists(2). waiting...\n');
pause(1);
end
temp = load(filename, 'id'); % third test.
if isequal(id, temp.id); break; end
fprintf('file lock exists(3). waiting...\n');
pause(1)
end
elseif isequal(op, 'remove')
%delete(filename);
execute_rs(@() delete(filename));
else
error('invalid op');
end
function execute_rs(f)
while true
try
lastwarn('');
f();
if ~isequal(lastwarn, ''); error(lastwarn); end %such as: Warning: File not found or permission denied
break;
catch exception
fprintf('Error: %s\n.Retrying...\n', exception.message);
pause(.5);
end
end
+++++++ +++++++++++++++++++++++++++++++++++
स्रोत
2010-08-10 18:26:17
मैं एक गीला कंबल होने के लिए नफरत है, लेकिन यह एक में सही पाने के लिए बहुत मुश्किल है सामान्य रूप से, विशेष रूप से नेटवर्क फ़ाइलों के लिए। फ़ाइल लॉकिंग अत्यधिक प्रणाली निर्भर है। कोई आसान, पहले से लागू समाधान नहीं होगा जो टूटा नहीं है। (ऐसा कुछ लिखना मुश्किल नहीं है जो "अधिकतर काम करता है"; ऐसा कुछ लिखना मुश्किल है जो उत्पादन में असफल नहीं होगा।) चलो एक पल वापस कदम: आप किस तक पहुंच को सिंक्रनाइज़ करने की कोशिश कर रहे हैं? क्या यह फ़ाइल सामग्री है, या फाइलें कुछ अन्य संसाधनों का प्रतिनिधित्व करती हैं? आप किस प्लेटफॉर्म को लक्षित कर रहे हैं? आपको "सही" कैसे बहिष्कार की आवश्यकता है? –