The file lock 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.
Use of file lock:
If one person is writing a file, another person also opens the file and writes to 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 shared location. I can read it, and so can others.
But, 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
Let’s take a look at the lock type:
Lock type | Description |
---|---|
LOCK_SH | Get shared lock (reading program) |
LOCK_EX | Get exclusive lock (writing program |
LOCK_UN | Release the lock (whether shared or exclusive) |
We next add an exclusive to demo.txt Lock, perform write operation.
<?php $fp = fopen("demo.txt", "r+"); // 进行排它型锁定 if (flock($fp, LOCK_EX)) { fwrite($fp, "文件这个时候被我独占了哟\n"); // 释放锁定 flock($fp, LOCK_UN); } else { echo "锁失败,可能有人在操作,这个时候不能将文件上锁"; } fclose($fp); ?>
Note:
1. In the above example, I added an exclusive lock to the file in order to write it.
2. If After my operation is completed and the writing is completed, the exclusive lock is released
3. If you are reading a file, you can add a shared lock according to the same processing idea.