note 41734 added to function.flock

From: Date: Wed, 21 Apr 2004 08:08:47 +0000
Subject: note 41734 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-68413@lists.php.net to get a copy of this message
A possible workaround for the missing filelock mechanism. Thanks to Bret below who gave me the idea to use fopen() with the 'x' option. I use this for logging in gzipped logfiles up to many hundreds of KBs (and some small counter files) since a few weeks without any problems (yet). But again ... this is not 100% save and will fail with a possible locked file when the script is aborted while the lock is created. This can however - when needed - been solved by creating a lock cleanup e.g. based on filetime. And writing to the file is not 100% sure: we give up after trying for a while - but what is on the net anyhow :). If you need something else than adding to the end of a file, use a callback function for rewriting the filecontent. And you might want to change the loop count and sleep time. NB: tested (and using) on WinXP, Linux and FreeBSD. <? 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 ($lf, '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+41734 Delete -- http://master.php.net/manage/user-notes.php?action=delete+41734&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+41734&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#68413) next »