Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous File Access

Tags:

php

Using:

fopen
fwrite
fclose

What happens if two users attempt to open the same file at the same time?

like image 315
ajsie Avatar asked Jan 14 '10 22:01

ajsie


3 Answers

Small-scale file operations are so quick that two writes at the exact same time are fairly rare. Regardless, you can use flock to lock the file:

$fp = fopen('file.log', 'a+');
flock($fp, LOCK_EX);
fwrite($fp, 'my data');
flock($fp, LOCK_UN);
fclose($fp);

Note fclose automatically unlocks the file, but the I find it makes the code a little more user-friendly to put these things in.

like image 145
Adam Hopkinson Avatar answered Oct 17 '22 15:10

Adam Hopkinson


What is important is:

  1. What happens when they write
  2. What happens if (a)reads, (b)reads then (b)writes then (a)writes? Is (a)'s write invalid because it's computation is no longer derived from the latest state?

The classic example is the Cash machine/bank balance example used in many texts.

Any kind of shared writable state requires some form of concurrent access control such as a mutex, but there are tons of potential problems such as race conditions, starvation and variations on the dining philosophers problem.

Many operating systems however allow File locking of some description, which means the other process waits for the lock to be released. See PHP's flock() for locking a file.

You can also use a "checkout, change, commit/merge" approach.

Depending on your reasons, you may want to consider a database such as MySQL or SQLite as these will provide faster, more robust ways to share state which is read-heavy or cache-less.

The numerous problems, pitfalls and ways of sharing state is vast. Apologies for all the Wikipedia usage.

like image 22
Aiden Bell Avatar answered Oct 17 '22 15:10

Aiden Bell


Use file_put_contents() instead with the FILE_APPEND or LOCK_EX flags.

Any of these flags lock the file for writing.

like image 38
Alix Axel Avatar answered Oct 17 '22 15:10

Alix Axel