note 84824 modified in function.flock by danbrown
| From: | danbrown@php.net | Date: | Thu, 31 Jul 2008 20:37:02 +0000 |
| Subject: | note 84824 modified in function.flock by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142988@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.
<?php
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;
}
}
?>
--was--
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;
}
}
http://php.net/manual/en/function.flock.php