note 43881 deleted from function.flock by danbrown

From: Date: Mon, 18 May 2009 00:45:05 +0000
Subject: note 43881 deleted from function.flock by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155424@lists.php.net to get a copy of this message
Note Submitter: jeroenl at see dot below ---- 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); } } ?>

« previous php.notes (#155424) next »