Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does LOCK_SH work?

Tags:

php

flock

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.

like image 626
Marius Popescu Avatar asked Dec 08 '13 10:12

Marius Popescu


People also ask

What is the use of flock function?

The flock() function locks and releases a file.

What is Lock_nb?

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.

Which flock () operation value releases an existing lock?

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 .

How do I lock a file in Perl?

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.


2 Answers

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.

like image 129
Mark Avatar answered Oct 11 '22 13:10

Mark


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

like image 29
worenga Avatar answered Oct 11 '22 13:10

worenga