How does LOCK_SH work?

Viewed 6417

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 Answers

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($)
Related