Example of using multiple processes to control file read/write simultaneously in php

Source: Internet
Author: User
Tags 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.