php uses multiple processes to control the file read and write example simultaneously

  • 2021-01-19 22:03:21
  • OfStack


<?php
/**
 *  Write data 
 * @param  [string] $path [ The 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."\r\n");
       flock($fp, LOCK_UN);
       fclose($fp);
       return true;
}

/**
 *  Read the data 
 * @param  [string] $path [ The 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+');


Related articles: