PHP file lock usage

Source: Internet
Author: User
Tags flock flock lock usleep

In PHP, the file lock and mysql table lock have the approximate usage, that is, only one person can operate at the same time, which avoids the operation of the same file by multiple people at the same time, this will cause data loss. Next I will introduce you to PHP file lock usage.

PHP comes with the file lock function:
Bool flock (int $ handle, int $ operation [, int & $ wouldblock])
$ Handle is the pointer to the opened file;
$ Operation can be
"LOCK_SH", shared lock; "LOCK_EX", exclusive lock; "LOCK_UN", release lock; "LOCK_NB" to prevent regular congestion of the flock lock.
Here we will mainly talk about "LOCK_EX" and "LOCK_NB ".

For example, we have two files.


Flocka. php

The Code is as follows: Copy code

$ File = 'temp.txt ';
$ Fp = fopen ($ file, 'A ');
 
For ($ I = 0; $ I <5; $ I ++)
{
Fwrite ($ fp, "111111n ");
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, and then run flockb. php immediately.
Result:
11111111
22222222
22222222
22222222
22222222
22222222
11111111
11111111
11111111
11111111
This indicates that when no filelock is applied, the two files write the txt files at the same time.
Next, modify the code of the two PHP files.
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, "111111n ");
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 );

Run flocka. php and then run flockb. php immediately.
We will find that flockb. php remains in the waiting state until the flocka. php operation is complete. flockb. php will continue to be executed only after the flocka. php operation is complete.
Output result:
11111111
11111111
11111111
11111111
11111111
22222222
22222222
22222222
22222222
22222222
In addition, when flock is executed, the file lock is automatically released.


There is another way


The following code simulates the transaction concurrency status: process1.php

The Code is as follows: Copy code
<? Php
$ Num = 100;
$ Filename = "processdata.txt ";
 
$ Fp = fopen ($ filename, "");
For ($ I = 0; $ I <$ num; $ I ++ ){
Fwrite ($ fp, "process1:". $ I. "rn ");
Usleep (100000 );
}
Fclose ($ fp );
?>

The statement must first execute the first transaction and write the 100 rows in the processdata.txt file.

Process2.php

The Code is as follows: Copy code

<? Php
$ Num = 100;
$ Filename = "processdata.txt ";
 
$ Fp = fopen ($ filename, "");
For ($ I = 0; $ I <$ num; $ I ++ ){
Fwrite ($ fp, "process2:". $ I. "rn ");
Usleep (100000 );
}
Fclose ($ fp );
?>

The second transaction is followed by writing 100 rows to the processdata.txt file.

The second transaction is followed by writing 100 rows to the processdata.txt file.

Although 100 rows are written at the same time, the data in transaction 1 and transaction 2 is staggered, which is not the expected result. What we need is the complete execution of the transaction. At this time, we need a mechanism to ensure that the second transaction is executed after the first transaction is executed. In PHP, flock functions fulfill this mission. Add flock ($ fp, LOCK_EX) before the loop of transaction 1 and transaction 2 to meet our needs and serialize two transactions.

When a transaction finishes flock execution, because LOCK_EX (exclusive lock) is added here, all operations on the resource will be blocked, only after the transaction is completed, the subsequent transactions will be executed. We can confirm this by outputting the current time.

For append write at the end, a concurrent write problem exists in earlier versions of the unix system. to append at the end, you must first append at the lseek position before writing. When multiple processes operate at the same time, the write overwrite issue will be caused by concurrency. That is, after both processes get the tail offset at the same time, the write operation will be executed successively, the subsequent operations will overwrite the previous operations. This problem is solved by adding the O_APPEND operation when opening. It turns the search and write operations into an atomic operation.

In the implementation of the fopen function in PHP, if we use the parameter to Append content to the end of the file, the oflag parameter in the call to the open function is O_CREAT | O_APPEND, that is, we do not need to worry about concurrent append writing when using the append operation.

The flock file lock is also used in the default session storage implementation of PHP. When the session starts, PS_READ_FUNC is called, and the session data file is opened with O_CREAT | O_RDWR | O_BINARY. the flock and write locks are called at this time, if another process accesses this file (that is, the same user initiates a request to the current file again), the page is loaded and the process is blocked. The starting point of the write lock is to ensure the complete execution of session operation transactions in this session, prevent interference from other processes, and ensure data consistency. If a page does not have a session modification operation, you can call session_write_close () to release the lock as soon as possible.

A file lock is a file lock. In addition to this definition, it can also be understood as a file lock. In actual work, sometimes to ensure the execution of a single process, we will determine whether the file exists before the execution of the program. If it does not exist, create an empty file, delete the empty file after the process ends. If it exists, it is not executed.

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.