필터 지우기
필터 지우기

Can a file be opened by two different programs simultaneously?

조회 수: 13 (최근 30일)
leonard_laney
leonard_laney 2021년 11월 17일
댓글: Walter Roberson 2021년 11월 20일
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

채택된 답변

Walter Roberson
Walter Roberson 2021년 11월 18일
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
Walter Roberson
Walter Roberson 2021년 11월 20일
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 2021년 11월 20일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by