I am trying to understand the right way to synchronize file read/write using the flock in PHP.
I have two php scripts.
echo "failed to lock\n";
echo "lock ok\n";
echo "acquired write lock\n";
echo "failed to acquire write lock\n";
You are using
fopen() with the
w mode in
testwrite.php. When using the
fopen() will truncate the file after opening it. (see
Because of that the file gets truncated in your example before you try to obtain the exclusive lock. However you'll need an open file descriptor in order to use
The way out of this dilemma is to use a lock file different from the file you are working on. The
flock() manual page mentions this:
Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).