0

So here it goes, I am developing a game that can be controlled via wi-fi. I was planning on modifying a file via a PhP webserver, this file is later read by a Python program in a constant loop detecting updates. So at a given moment both the python program and the webserver will open the same file, so there goes my question...

This is basically the Python code that i will use:

file = open('file.ext', 'r')
answer = file.readline()
file.close()

And the PhP Code:

$dir = $_POST['dir'];
$file = fopen('file.ext', 'w+');

switch ($dir) {
     case 'up':
         fwrite($file, 'up');
         break;
    case 'down':
         fwrite($file, 'down');
         break;
    case 'left':
         fwrite($file, 'left');
         break;
    case 'right':
         fwrite($file, 'right');
         break;
  }
fclose($file);
10 Rep
  • 2,217
  • 7
  • 19
  • 33
Chromz
  • 183
  • 3
  • 11

2 Answers2

1


Avoid accessing the file at the same time in two programs. Because some problems might occure. Just think that in the same time we read and write.

This kind of problems are known as "Mutual Exclusion" means that some resources (for example: a file) must be in access for just one program (or process).
So you can use known solutions of Mutual Exclusion like "Semaphore" or "Lock". See below links for more information:

PHP mutual exclusion (mutex) PHP Mutual Exclusion on a File / MySQL reading and executing statements from a file using perl Mutual exclusion thread locking, with dropping of queued functions upon mutex/lock release, in Python? http://wiki.bash-hackers.org/howto/mutex

Community
  • 1
  • 1
Fartab
  • 4,725
  • 2
  • 26
  • 39
0

It's okay to ACCESS the file from two different programs, as long as you don't try to MODIFY it from two different programs. From what I see of your code, you are only reading from Python, not writing - your writing is only in PHP. Therefore, you should not have any conflicts. However, you should still make sure to use a file-locking mechanism to give the PHP a write-lock on the file so that no other programs can cause conflicts.

BIU
  • 2,340
  • 3
  • 17
  • 23