How does flock work?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
budgefeeney
Forum Newbie
Posts: 7
Joined: Tue Apr 06, 2004 9:08 am

How does flock work?

Post by budgefeeney »

I'm writing a program, part of which updates a log file. I'm using [php_man]flock[/php_man] to lock the files in case of simultaneous writes.

However there's one thing I wonder about.

If someone else has locked the file, does [php_man]flock[/php_man] return false immediately, or does it wait for a predefined limit and then, if the file is still locked, return false.

If is is the former, should I be writing:

Code: Select all

$handle = fopen ("path/to/logfile.log", "w");
while (! flock ($handle, LOCK_EX))
   ;

fwrite ($handle, "Log-entry"); // etc.

flock ($handle, LOCK_UN);
fclose ($handle);
Thanks
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

PHP manual wrote: ....
If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation .
....
Thus, by default flock would block, but if you explicitly say to not block - it wouldn't
Post Reply