I'm studing the flock mecanism in PHP and I'm having a hard time understanding the functionality of the LOCK_SH mode. I read on a site that it locks the file so that other scripts cannot WRITE in it, but they can READ from it. However the following code didn't seem to work as expected : In file1.php I have:
$fp = fopen('my_file.txt','r');
flock($fp, LOCK_SH);
sleep(20);
flock($fp, LOCK_UN);
And in file2.php I have
$fp = fopen('my_file.txt','a');
fwrite($fp,'test');
I run the first script which locks the file for 20 seconds. With the lock in place, I run file2.php which finishes it's execution instantly and after that, when I opened 'my_file.txt' the string 'test' was appended to it (althought the 'file1.php' was still runing). I try to change 'file2.php' so that it would read from the locked file and it red from it with no problems. So apparently ... the 'LOCK_SH' seams to do nothing at all. However, if I use LOCK_EX yes, it locks the file, no script can write or read from the file. I'm using Easy PHP and running it under windows 7.
The flock() function locks and releases a file.
LOCK_NB means non-blocking. Usually when you try to lock a file, your PHP script execution will stop. The call to flock() then blocks it from resuming. It does so until a concurrent lock on the accessed file is removed.
flock() applies or removes an advisory lock on the file associated with the file descriptor fd . A lock is applied by specifying an operation parameter that is one of LOCK_SH or LOCK_EX with the optional addition of LOCK_NB . An existing lock is removed using the LOCK_UN operation .
File locking can be done, in Perl, with the flock command. flock() accepts two parameters. The first one is the filehandle. The second argument indicates the locking operation required.
flock()
implements advisory locking, not mandatory locking. In order for file2.php
to be blocked by file1.php
's lock, it needs to try to acquire a write (LOCK_EX)
lock on the file before writing.
LOCK_SH means SHARED LOCK. Any number of processes MAY HAVE A SHARED LOCK simultaneously. It is commonly called a reader lock.
LOCK_EX means EXCLUSIVE LOCK. Only a single process may possess an exclusive lock to a given file at a time.
If the file has been LOCKED with LOCK_SH in another process, flock with LOCK_SH will SUCCEED. flock with LOCK_EX will BLOCK UNTIL ALL READER LOCKS HAVE BEEN RELEASED.
http://php.net/manual/en/function.flock.php#78318
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With