File locking mechanism
File Locking Mechanism
The file locking mechanism generally has no effect at all when a single file is opened. This part of learning is a little abstract.
Don’t think about how to achieve it?
Why can’t I see the effect?
Answer: Because the computer operates so fast, basically on the millisecond level. So this experiment actually has no effect.
In this chapter, just understand the basic concepts of file locking and become familiar with the file locking function and locking mechanism.
The purpose of file lock:
If one person is writing a file, another person also writes to the file at the same time Import the file.
In this case, if a certain collision probability is encountered, I don’t know whose operation will prevail.
Therefore, we introduce the lock mechanism at this time.
If user A writes or reads this file, add the file to the share. I can read it, and so can others.
However, if this is the case. I use exclusive lock. This file belongs to me. Don't touch it unless I release the file lock.
Note: Regardless of whether the file lock is added, be careful to release it.
Let’s take a look at this function:
bool flock (resource $handle, int $operation)
Function: lightweight advisory file locking
We Let’s take a look at the lock type:
<?php $fp = fopen("demo.txt", "r+"); // 进行排它型锁定 if (flock($fp, LOCK_EX)) { fwrite($fp, "文件这个时候被我独占了哟\n"); // 释放锁定 flock($fp, LOCK_UN); } else { echo "锁失败,可能有人在操作,这个时候不能将文件上锁"; } fclose($fp); ?>Explanation: 1. In the above example, in order to write the file, I added an exclusive lock to the file. 2. If my operation is completed and the writing is completed, the exclusive lock will be released. 3. If you are reading a file, you can add a shared lock according to the same processing idea.