Using:
fopen
fwrite
fclose
What happens if two users atte开发者_StackOverflowmpt to open the same file at the same time?
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.
What is important is:
- What happens when they write
- 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.
Use file_put_contents()
instead with the FILE_APPEND
or LOCK_EX
flags.
Any of these flags lock the file for writing.
Yes you can open two files at the same time unless you lock the file [flock]. Yet, the best time to flock a file would be when you are writing to it, or if you so choose to only allow one user to view a file at any one point.
Happens all the time. However the answer to your question depends on what exactly both want/would want to do with the opened file. The possible actions/solutions will purely depend on the this requirement.
精彩评论