PHP file Lock usage detailed _php tutorial

Source: Internet
Author: User
Tags flock usleep
PHP file lock and MySQL table lock have probably want to use, that is, only one person to operate at the same time, so as to avoid the simultaneous operation of the same file, so that the loss of data situation, let me introduce you to the PHP file lock usage.

PHP comes with a file lock function:
BOOL Flock (int $handle, int $operation [, int & $wouldblock])
$handle is the open file pointer;
$operation can be
"Lock_sh", shared lock, "LOCK_EX", exclusive lock, "Lock_un", Release lock, "LOCK_NB" to prevent blockage when flock is locked.
Here the main talk about "LOCK_EX" and "LOCK_NB".

For example, we have two files, as follows.


flocka.php

The code is as follows Copy Code

$file = ' temp.txt ';
$fp = fopen ($file, ' a ');

for ($i = 0; $i < 5; $i + +)
{
Fwrite ($fp, "11111111n");
Sleep (1);
}

Fclose ($FP);

flockb.php

The code is as follows Copy Code
$file = ' temp.txt ';
$fp = fopen ($file, ' a ');

for ($i = 0; $i < 5; $i + +)
{
Fwrite ($fp, "22222222n");
}

Fclose ($FP);

Run flocka.php first, then run flockb.php immediately.
Results:
11111111
22222222
22222222
22222222
22222222
22222222
11111111
11111111
11111111
11111111
Note When no file lock is added, two files write to the TXT file at the same time.
Modify the code for the two PHP files below.
flocka.php

The code is as follows Copy Code
$file = ' temp.txt ';
$fp = fopen ($file, ' a ');

if (Flock ($FP, LOCK_EX))
{
for ($i = 0; $i < 5; $i + +)
{
Fwrite ($fp, "11111111n");
Sleep (1);
}
Flock ($FP, lock_un);
}
Fclose ($FP);

flockb.php

The code is as follows Copy Code
$file = ' temp.txt ';
$fp = fopen ($file, ' a ');

if (Flock ($FP, LOCK_EX))
{
for ($i = 0; $i < 5; $i + +)
{
Fwrite ($fp, "22222222n");
}
Flock ($FP, lock_un);
}

Fclose ($FP);

Also run flocka.php first, and then run flockb.php immediately.
You will find that flockb.php is waiting until the end of the flocka.php run, and flockb.php will not continue until the flocka.php is finished.
Output Result:
11111111
11111111
11111111
11111111
11111111
22222222
22222222
22222222
22222222
22222222
In addition, when the flock is executed, the file lock is automatically released.


There's another way.


The following code simply simulates the concurrency state of this transaction: process1.php

The code is as follows Copy Code
$num = 100;
$filename = "Processdata.txt";

$fp = fopen ($filename, "a");
for ($i = 0; $i < $num; $i + +) {
Fwrite ($FP, "Process1:".) $i. "RN");
Usleep (100000);
}
Fclose ($FP);
?>

We need to execute the first transaction and write the 100 lines in the Processdata.txt file.

process2.php

The code is as follows Copy Code

$num = 100;
$filename = "Processdata.txt";

$fp = fopen ($filename, "a");
for ($i = 0; $i < $num; $i + +) {
Fwrite ($FP, "Process2:".) $i. "RN");
Usleep (100000);
}
Fclose ($FP);
?>

The second transaction continues to write 100 rows to the Processdata.txt file.

The second transaction continues to write 100 rows to the Processdata.txt file.

It is executed at the same time, although both write 100 rows, but the data of transaction 1 and Transaction 2 is interleaved, this is not the result we want. What we want is a complete execution of the transaction, at which point we need to have a mechanism to ensure that the second one is executed after the first transaction is executed. In PHP, the Flock function accomplishes this mission. Add in front of the cycle of things 1 and 2: Flock ($FP, LOCK_EX); will be able to meet our needs, the two transaction serial.

When a transaction finishes executing flock, because we are adding a LOCK_EX (exclusive lock) Here, all operations on the resource are blocked and the subsequent transaction executes only after the transaction has finished executing. We can confirm this by outputting the current time method.

With regard to appending writes at the tail, there is a problem of concurrent writes in earlier versions of the UNIX system, and if you want to append at the end, you need to lseek the location before writing. When multiple processes are operating concurrently, the write operation is performed after the two process obtains the trailing offset in parallel because of concurrency-induced overwrite writes, and subsequent operations overwrite the preceding action. This problem is resolved later by adding an open o_append operation, which turns the find and write operations into an atomic operation.

In the implementation of PHP's fopen function, if we append content to the end of the file using the A parameter, the Oflag parameter in the Open function is called o_creat| O_append, that is, we use append operations without worrying about concurrent append writes.

The flock file lock is also used in the session default storage implementation of PHP, and is called when the session starts, and Ps_read_func is O_creat | O_rdwr | O_binary open Session data file, this time will call flock Plus write lock, if there is another process to access this file (that is, the same user initiates a request to the current file), the page load is displayed, the process is blocked. Write-lock Its starting point is to ensure that the session in the operation of the transaction can be fully executed, to prevent interference from other processes, to ensure consistency of data. If a page does not have a session modification operation, the Session_write_close () release lock can be called as soon as possible.

A file lock is a lock on a file, and in addition to this interpretation, it can be understood as a file as a lock. In practice, sometimes to ensure the execution of a single process, we will determine whether the file exists before the program executes, if it does not exist, create an empty file, delete the empty file after the process is finished, and do not execute if it exists.

http://www.bkjia.com/PHPjc/628753.html www.bkjia.com true http://www.bkjia.com/PHPjc/628753.html techarticle php file lock and MySQL table lock have probably want to use, is the same time only one person to operate, so as to avoid the simultaneous operation of the same file, so that the loss of data ...

  • 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.