PHP writes a piece of code to ensure that multiple processes write to a file successfully at the same time

Source: Internet
Author: User
Tags flock

This requirement is a common locking in the software design process.
Computer students should know that this is in the "Computer operating system" course has this knowledge point.
The main consideration is the process synchronization, that is, the process mutually exclusive access to the resource.
OK, speak with the program!


<?php
function WriteFile ($filename, $data) {
$fp = fopen ($filepath, ' a '); Opens the file as an append, and returns a pointer
do{
Usleep (100); Suspends execution of the program with parameters in microseconds
}while (!flock ($fp, LOCK_EX)); Locks the file in exclusive write mode, returns true if successful, otherwise false
}
$res = fwrite ($fp, $data. "  /n "); Writes data to an open file in an append way
Flock ($FP, lock_un); Unlock to allow other processes to lock
Fcloce ($FP); Close the Open file pointer
return $res; Return write results
?>

OK, the code is not too much! This is not a code, it is important to understand the meaning of each function, as well as the meaning of each statement.

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.