Page 1 of 1

How does flock work?

Posted: Tue Apr 06, 2004 9:08 am
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

Posted: Tue Apr 06, 2004 10:52 am
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