Php uses multiple processes to simultaneously control file read/write. Example _ php instance

Source: Internet
Author: User
Tags flock usleep
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 + ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.