Home Backend Development PHP Tutorial flock — lightweight advisory file locking_PHP tutorial

flock — lightweight advisory file locking_PHP tutorial

Jul 13, 2016 am 10:29 AM
php

bool flock ( resource $handle , int $operation [, int &$wouldblock ] )

handle
The file system pointer is a resource typically created by fopen().

operation can be one of the following values:
1. LOCK_SH obtains the shared lock (reading program).
2. LOCK_EX Obtains an exclusive lock (writing program.
3. LOCK_UN Releases the lock (whether shared or exclusive).
4. If you do not want flock() to block when locking, it is LOCK_NB ( Not yet supported on Windows).

wouldblock
If the lock would block (in case of EWOULDBLOCK error code), the optional third parameter will be set to TRUE (not supported on Windows)<.>
Return value
Returns TRUE on success, or FALSE on failure.


Prior to PHP 5.3.2, the lock will also be released by fclose() (in the script). will be called automatically after completion), now unlocking must be done manually (flock ( $fp , LOCK_UN ); // Release the lock).
When using a multi-threaded server API (such as ISAPI), flock( may not be relied on. ) to protect the file because PHP scripts running in other parallel threads in the same server instance can process the file (?)


eg:1
file_get_contents and file sometimes read a. If the file is not empty, it will return empty. For example,
During the locking period of code1, the output of code2 is empty. Code3 will wait for code1 to release the lock and return the obtained content
code1

<?<span>php
</span><span>$fo</span> = <span>fopen</span>('abc.txt', 'r+'<span>);
</span><span>flock</span>(<span>$fo</span>,<span> LOCK_EX);
</span><span>sleep</span>(10<span>);
</span><span>flock</span>(<span>$fo</span>, LOCK_UN);
Copy after login

code2

<?<span>php
</span><span>var_dump</span>(<span>file_get_contents</span>('abc.txt'<span>));
</span><span>var_dump</span>(<span>file</span>('abc.txt'));
Copy after login
code3

<?<span>php
</span><span>$con</span> = getContents('abc.txt'<span>);
</span><span>print_r</span>(<span>$con</span><span>);

</span><span>function</span> getContents(<span>$path</span>, <span>$waitIfLocked</span> = <span>true</span><span>) {
    </span><span>if</span>(!<span>file_exists</span>(<span>$path</span><span>)) {
        </span><span>throw</span> <span>new</span> <span>Exception</span>('File "'.<span>$path</span>.'" does not exists'<span>);
    }
    </span><span>else</span><span> {
        </span><span>$fo</span> = <span>fopen</span>(<span>$path</span>, 'r'<span>);
        </span><span>$locked</span> = <span>flock</span>(<span>$fo</span>, LOCK_SH, <span>$waitIfLocked</span><span>);
         
        </span><span>if</span>(!<span>$locked</span><span>) {
            </span><span>return</span> <span>false</span><span>;
        }
        </span><span>else</span><span> {
            </span><span>$cts</span> = <span>file_get_contents</span>(<span>$path</span><span>);
             
            </span><span>flock</span>(<span>$fo</span>,<span> LOCK_UN);
            </span><span>fclose</span>(<span>$fo</span><span>);
             
            </span><span>return</span> <span>$cts</span><span>;
        }
    }
} </span>
Copy after login

eg:2
The running result of this machine is inconsistent with the following. It can be written during LOCK_SH (???)
The following is an example in the manual
I just spend a long time to understand why write function returns me "0", on a basic file opening and then writing.
I discovered that if you use LOCK_SH and then you write something, that will not work :

<?<span>php
</span><span>$fp</span> = <span>fopen</span>('file.txt', 'a'<span>);

</span><span>flock</span>(<span>$fp</span>,<span>LOCK_SH);

</span><span>$written</span> = <span>fputs</span>(<span>$fp</span>, 'data'<span>);

</span><span>var_dump</span>(<span>$written</span>); <span>//</span><span> 0 and file is not changed</span>

<span>fclose</span>(<span>$fp</span>);
Copy after login

eg:3

Write code to solve the problem of multiple processes and threads reading and writing a file at the same time ​Question:
PHP does not have the concept of multi-threading. However, we can still use "imperfect" methods to simulate multi-threading.
To put it simply, it is queue processing. This is achieved by locking and unlocking files. When a file is operated by a user,
the file is locked, and other users can only wait. It is indeed not perfect, but it can also meet some applications with low requirements

<?<span>php
</span><span>function</span> T_put(<span>$filename</span>,<span>$string</span><span>){  
</span><span>$fp</span> = <span>fopen</span>(<span>$filename</span>,&rsquo;a'<span>); //追加方式打开  
if (flock($fp, LOCK_EX)){ //加写锁  
fputs($fp,$string); //写文件  
flock($fp, LOCK_UN); //解锁  
}  
fclose($fp);  
}  

function T_get($filename,$length){  
$fp = fopen($filename,&rsquo;r</span>'); <span>//</span><span>追加方式打开  </span>
<span>if</span> (<span>flock</span>(<span>$fp</span>, LOCK_SH)){ <span>//</span><span>加读锁  </span>
<span>$result</span> = <span>fgets</span>(<span>$fp</span>,<span>$length</span>); <span>//</span><span>读取文件  </span>
<span>flock</span>(<span>$fp</span>, LOCK_UN); <span>//</span><span>解锁  </span>
<span>}  
</span><span>fclose</span>(<span>$fp</span><span>);  
</span><span>return</span> <span>$result</span><span>;  
}</span>
Copy after login

http://www.bkjia.com/PHPjc/769340.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/769340.htmlTechArticlebool flock ( resource $handle , int $operation [, int $wouldblock ] ) handle file system pointer, which is a typical A resource created by fopen(). operation can be one of the following values...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term Impact PHP and the Web: Exploring its Long-Term Impact Apr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

See all articles