PHP uses multiple processes to control file reading and writing at the same time_PHP tutorial

WBOY
Release: 2016-07-13 10:36:56
Original
1017 people have browsed it

复制代码 代码如下:

/**
* Write data
* @param [string] $path [file path]
* @param [string] $mode [file open mode]
* @param [string] $data [ Data]
* @return [bool] 
*/
function writeData($path, $mode, $data){
       $fp = fopen($path, $mode);
       $retries = 0;
       $max_retries = 100;
       do {
        if ($retries > 0) {
         usleep(rand(1, 10000));
        }
        $retries += 1;
       }while (!flock($fp, LOCK_EX) and $retries <= $max_retries);
       if ($retries == $max_retries) {
        return false;
       }
       fwrite($fp, $data."rn");
       flock($fp, LOCK_UN);
       fclose($fp);
       return true;
}


/**
* Read data
* @param [string] $path [file path]
* @param [string] $mode [file open mode]
* @return string
*/
function readData($path,$mode){
     $fp = fopen($path, $mode);
     $retries = 0;
     $max_retries = 100;
     do {
      if ($retries > 0) {
       usleep(rand(1, 10000));
      }
      $retries += 1;
     }while (!flock($fp, LOCK_SH) and $retries <= $max_retries);
     if ($retries == $max_retries) {
      return false;
     }
     $contents = "";
     while (!feof($fp)) {
        $contents .= fread($fp, 8192);
     }
     flock($fp, LOCK_UN);
     fclose($fp);
     return $contents;
}

writeData('D:/webServer/demo.txt','a+','this is a demo');
echo readData('D:/webServer','r+');

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/736838.htmlTechArticle复制代码 代码如下: ?php /** * 写入数据 * @param [string] $path [文件路径] * @param [string] $mode [文件打开模式] * @param [string] $data [数据] * @return [b...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!