This article mainly introduces the example of using multiple processes to simultaneously Control File Read/write in php. For more information, see
The Code is as follows:
/**
* Write data
* @ Param [string] $ path [file path]
* @ Param [string] $ mode [file opening 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 data
* @ Param [string] $ path [file path]
* @ Param [string] $ mode [file opening 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 + ');