Effacer les filtres
Effacer les filtres

Can a file be opened by two different programs simultaneously?

13 vues (au cours des 30 derniers jours)
leonard_laney
leonard_laney le 17 Nov 2021
Commenté : Walter Roberson le 20 Nov 2021
Hi I'm making a simple shooter game in matlab for a school project and I'm wondering if two different instances of a program can access a file simultaneously? It's a two player game and the two players can only communicate through files using fscanf and fprintf which is a requirement. So player 1 moves, writes his position to his file, and player 2 will read that position from player 1's file so he knows where to draw the enemy character. Player 1 is the only one who can write to his file, the same applies to player 2.
I was running into issues where sometimes a player can't read a valid number from the file and I assumed that whenever a player is writing to his file, the other player can't access it. I solved the issue with a while loop to continuously try and grab a number until it is valid. Am I wrong in thinking that a file can't be read from whilst it's currently being written to?
Code:
function [num] = readNum(fname,size,formatSpec)
%readNum reads numerical data from file
%Input Arguments
% fname - name of file passed from main function
% size - size of array being read
% formatSpec - format specifier
%Output Arguments
% num - number can be a scalar, vector, or matrix
fin = fopen(fname,'r');
%only close file when valid number is read
%It waits until file is no longer being written to
num = fscanf(fin,formatSpec,size)';
while isempty(num)
close(fin)
fin = fopen(fname,'r');
num = fscanf(fin,formatSpec,size)';
end
fclose(fin);
end

Réponse acceptée

Walter Roberson
Walter Roberson le 18 Nov 2021
If you are using Windows, then it has mandatory locking, and a file that is opened for writing by one process cannot be opened for reading by a different process — not unless the writing process deliberately makes the file readable.
Linux and Mac work differently.
  3 commentaires
Walter Roberson
Walter Roberson le 20 Nov 2021
Maybe? I would not rule out the possibility of there being a .NET method of doing it that you could invoke from MATLAB. Certainly no Mathworks provided methods.
If you were to use memmapfile() then possibly those would be automatically shared, maybe? But you cannot use the same i/o calls required by the assignment if you use those functions.
Walter Roberson
Walter Roberson le 20 Nov 2021
If you do not have access to the file unlocking system, then work-around for windows to prevent conflicts and be reliable, is to use a different file for each turn for each side.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by