note 84824 added to function.flock

From: Date: Thu, 31 Jul 2008 20:36:26 +0000
Subject: note 84824 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-142987@lists.php.net to get a copy of this message
Here's a handy class to allow retrying a write with flock a set number of times. If it can't flock, it will sleep for a brief random interval and try again. If you have a lot of concurrent writes going on, you can use it to avoid data corruption. class SafeWriter { // suggested mode 'a' for writing to the end of the file public static function writeData($path, $mode, $data) { $fp = fopen($path, $mode); $retries = 0; $max_retries = 100; if (!$fp) { // failure return false; } // keep trying to get a lock as long as possible do { if ($retries > 0) { usleep(rand(1, 10000)); } $retries += 1; } while (!flock($fp, LOCK_EX) and $retries <= $max_retries); // couldn't get the lock, give up if ($retries == $max_retries) { // failure return false; } // got the lock, write the data fwrite($fp, "$data\n"); // release the lock flock($fp, LOCK_UN); fclose($fp); // success return true; } } ---- Server IP: 208.69.120.35 Probable Submitter: 209.251.128.198 ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- https://master.php.net/note/edit/84824 Del: integrated -- https://master.php.net/note/delete/84824/integrated Del: useless -- https://master.php.net/note/delete/84824/useless Del: bad code -- https://master.php.net/note/delete/84824/bad+code Del: spam -- https://master.php.net/note/delete/84824/spam Del: non-english -- https://master.php.net/note/delete/84824/non-english Del: in docs -- https://master.php.net/note/delete/84824/in+docs Del: other reasons-- https://master.php.net/note/delete/84824 Reject -- https://master.php.net/note/reject/84824 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#142987) next »