How does LOCK_SH work?

7.4k views Asked by At

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.

3

There are 3 answers

1
Mark On BEST ANSWER

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.

2
worenga On

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

2
zloctb On

We use LOCK_SH for reading file . If something writting in this file in this time this type blocking wait finish operation writting and after that unlock and we can read .
If something no writting in this file locked don't set!

 <?php ## Модель процесса-читателя
    $file = "file.txt";
    // Вначале создаем пустой файл, ЕСЛИ ЕГО ЕЩЕ НЕТ.
    // Если же файл существует, это его не разрушит.
    fclose(fopen($file, "a+b"));
    // Блокируем файл
    $f = fopen($file, "r+b") or die("Не могу открыть файл!");
    flock($f, LOCK_SH); // ждем, пока не завершится писатель
    // В этой точке мы можем быть уверены, что в файл
    // никто не пишет
    // Все сделано. Снимаем блокировку.
    fclose($)