Analysis of flock() function in PHP (with code examples)

autoload
Release: 2023-04-09 22:24:01
Original
2782 people have browsed it

Analysis of flock() function in PHP (with code examples)

In the process of using PHP, we often need to read files, but in order to prevent other processes from reading and modifying files and avoiding conflicts, we must read files before The file is locked when fetching, and then the file is modified until the operation is completed. The flock() function is used in this process. This article will take you to understand the following. For the first time, let's take a look at the syntax of the block() function:

flock( resource $handle, int $operation, int $wouldblock = ?)
Copy after login
  • $handle: file system pointer, typically used by fopen() Created resource(resource).

  • $operation: LOCK_SH Obtain shared lock (reading program). LOCK_EX Obtains an exclusive lock (writing program. LOCK_UN Releases the lock (whether shared or exclusive). If you do not want flock() to block while locking, then Is LOCK_NB (not supported on Windows yet).

  • $wouldblock: If the lock will block (in case of EWOULDBLOCK error code), the optional third The parameter will be set to true. (Not supported on Windows)

  • Return value: Returns true on success, or returns on failure false.

Code example:

1. Use LOCK_EX

<?php
$fp = fopen("exit.txt", "r+");
if (flock($fp, LOCK_EX)) {  // 进行排它型锁定
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // 释放锁定
} else {
    echo "Couldn&#39;t get the lock!";
}
fclose($fp);
?>
Copy after login
exit.text内容:Write something here
Copy after login

2. Use LOCK_NB

<?php
$fp = fopen(&#39;exit.txt&#39;, &#39;r+&#39;);

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
    echo &#39;Unable to obtain lock&#39;;
    exit(-1);
}

fclose($fp);


?>
Copy after login

Recommended: 2021 Summary of PHP interview questions (Collection)》《php video tutorial

The above is the detailed content of Analysis of flock() function in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template