avoiding simultaneous access to the same file
Mostra commenti meno recenti
I need to have a log file that is accessed by a few (about 10-15) programs (each I run from its own windows XP command window, each is run by launching the compiled .exe file) that are running together. Each needs to report something (a short, about 100 characters, into a comma separated value file (.csv))every couple of minutes.
I tried the following code for a common function and it seemed to work, however there are glitches every now and then where I see that messages got into one another as if the file 'locking' does not work perfectly.
Can someone tell me why that is, and perhaps has a better or corrected implementation to recommend?
Thanks
P.S.
I am running on Windows XP, with version R2009b
if true
% code
end
function [success]=write_to_log(message_type,message_id,varargin)
% write_to_log used for reporting to errors and information to a log file.
global LOG_FILE;
global MAX_DELAY_BETWEEN_TRYS; %set to 2
global MINIMUM_TO_MAX_DELAY; %set to 0.9
global N_TRYS; %set to 8
time_recieved=now;%time of reporting (will not depend on delay caused by accessing the file
%try and open the log file n_trys
for i=1:N_TRYS
file_id=fopen(LOG_FILE,'a');
if file_id ~= -1 %if succeeded in opening file
fprintf(file_id,'%s', datestr(time_recieved,'yyyy-mm-dd HH:MM:SS'));% report time %'yyyy-mm-dd HH:MM:SS.FFF'
fprintf(file_id,',%s', lower(message_type)); %report type ('error', 'info')
fprintf(file_id,',%s', lower(message_id));% report id;
for k= 1 : size(varargin,2)% print all the remaining optional parameters if they were sent to the function
fprintf(file_id,',%s', lower(varargin{k}));
end
fprintf(file_id,'\r\n');% send an end of line to end the line.
fclose(file_id);%close so that others an access the file.
success=1;%report the function succeeded
%disp(i)
return
end
%disp(['failed attempt ' char(i) ' to open log for writting'])
time_delay=MAX_DELAY_BETWEEN_TRYS * ( MINIMUM_TO_MAX_DELAY+(1-MINIMUM_TO_MAX_DELAY)*rand(1));
pause(time_delay) % wait between attempts to open the file
end
success=0; %failed to open file in order to report to log
end
1 Commento
Why not logging in separate files with a time stamp ( datenum(now) ) for each entry, and create an additional log manager (reader/parser) which merges logs based on time stamps? The latter would be easy to implement: it would be basically concatenating all files and sorting by time stamp. And the whole approach would create more accurate logs as the order of entries would not depend on when one process can (finally) access the log file.
Risposte (0)
Categorie
Scopri di più su Work with Components in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!