note 46085 added to function.flock

From: Date: Tue, 28 Sep 2004 23:04:11 +0000
Subject: note 46085 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-77545@lists.php.net to get a copy of this message
<?php /* * I hope this is usefull. * If mkdir() is atomic, * then we do not need to worry about race conditions while trying to make the lockDir, * unless of course were writing to NFS, for which this function will be useless. * so thats why i pulled out the usleep(rand()) peice from the last version * * Again, its important to tailor some of the parameters to ones indivdual usage * I set the default $timeLimit to 3/10th's of a second (maximum time allowed to achieve a lock), * but if your writing some extrememly large files, and/or your server is very slow, you may need to increase it. * Obviously, the $staleAge of the lock directory will be important to consider as well if the writing operations might take a while. * My defaults are extrememly general and you're encouraged to set your own * * $timeLimit is in microseconds * $staleAge is in seconds * * */ function microtime_float() { list($usec, $sec) = explode(' ', microtime()); return ((float)$usec + (float)$sec); } function locked_filewrite($filename, $data, $timeLimit = 300000, $staleAge = 5) { ignore_user_abort(1); $lockDir = $filename . '.lock'; if (is_dir($lockDir)) { if ((time() - filemtime($lockDir)) > $staleAge) { rmdir($lockDir); } } $locked = @mkdir($lockDir); if ($locked === false) { $timeStart = microtime_float(); do { if ((microtime_float() - $timeStart) > $timeLimit) break; $locked = @mkdir($lockDir); } while ($locked === false); } $success = false; if ($locked === true) { $fp = @fopen($filename, 'a'); if (@fwrite($fp, $data)) $success = true; @fclose($fp); rmdir($lockDir); } ignore_user_abort(0); return $success; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46085 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46085&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+46085&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#77545) next »