note 43881 added to function.flock
| From: | jeroenl at see dot below | Date: | Wed, 07 Jul 2004 09:16:54 +0000 |
| Subject: | note 43881 added to function.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-72815@lists.php.net to get a copy of this message | ||
lockwang, thanx for pointing out the bug I forgot to update overhere.
I agree (as mentioned) that an old not unlinked lockfile will stop writing, but at least writing
will never corrupt old data and if needed you can add a lock clean up.
If you want uncorrupted files and a possible data loss is not a very big problem (like with traffic
logging, etc.) this solution does work.
After trying a lot of things (always corrupting files) I use this code now since a few months for
loggings and counters on many sites, resulting in (gzipped) files up to 2 Mb, without any corrcupted
file or any not unlinked lockfile yet (knock knock...).
A better solution (100% save would be nice :) would be great, but since I haven't seen one
around yet ...
If more is needed SQLite (if available) might be an alternative.
Corrected code:
<?
function fileWrite($file, &$str, $lockfile = null) {
// ceate a lock file - if not possible someone else is active so wait (a while)
$lock = ($lockfile)? $lockfile : $file.'.lock';
$lf = @fopen ($lock, 'x');
while ($lf === FALSE && $i++ < 20) {
clearstatcache();
usleep(rand(5,85));
$lf = @fopen ($lock, 'x');
}
// if lockfile (finally) has been created, file is ours, else give up ...
if ($lf !== False) {
$fp = fopen( $file, 'a');
fputs( $fp, $str); // or use a callback
fclose( $fp);
// and unlock
fclose($lf);
unlink($lock);
}
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.flock.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+43881
Delete -- http://master.php.net/manage/user-notes.php?action=delete+43881&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+43881&report=yes
Search -- http://master.php.net/manage/user-notes.php