This article mainly introduces it. Interested friends can refer to it. I hope it will be helpful to everyone.
The example in this article describes how PHP uses flock to implement file locking. Share it with everyone for your reference. The specific analysis is as follows:
Flock’s explanation in the official documentation is: flock() allows you to implement a simple read/write model that can be used on any platform (including most Unix derivatives and Even Windows). If the lock will block (in case of EWOULDBLOCK error code), set the optional third parameter to TRUE. Lock operations can also be released by fclose() (also called automatically when the code completes execution).
Simply put, it is to lock a file so that multiple processes are restricted from accessing the file, thereby preventing conflicts. For example:
<?php $file = fopen("test.txt","w+"); if (flock($file,LOCK_EX)) { fwrite($file,"Write something"); flock($file,LOCK_UN); } else { echo "Error locking file!"; } fclose($file); ?>
Explanation:
1. The meaning of this code is to open the file test.txt in read and write mode. When a user calls the php page, it will open the file test.txt. .txt file, the flock($file,LOCK_EX) code will be executed, which will exclusively lock the test.txt file (the file can only be read and written by this user), then if other new users want to access The file will be blocked until the former closes the file (releases the lock).
2. If the code is changed to flock($file,LOCK_EX LOCK_NB) to indicate that an error will be returned directly when locking, then if a new user accesses the file, "Error locking file!" will be output.
3. The syntax of this function is flock(file,lock,block), where file is required. Specifies an open file to be locked or released. lock required. Specifies which lock type to use. block is optional. If set to 1 or true, blocks other processes while locking.
For example: Please write a piece of PHP code to ensure that multiple processes can write the same file successfully at the same time
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\n"); flock($fp, LOCK_UN); fclose($fp); return true; }
Summary:The above is the entire content of this article, I hope It can be helpful to everyone’s study.
Related recommendations:
How to operate dates and strings in php
php tool to implement web page caching Class code and usage
php controls all background function calls based on ajax
The above is the detailed content of How to use PHPflock file lock. For more information, please follow other related articles on the PHP Chinese website!