A file lock is a file read/write mechanism that allows only one process to access one file at any specific time. Using this mechanism can make the process of reading and writing a single file more secure.
In this article, we will explore different types of File locks in Linux and use the example program to understand the differences between them.
We will take the following example to explain why file locks are needed.
1. process "a" to open and read a file, which contains information related to the account.
2. Process "B" also opened the file and read the information in the file.
3. Now, process "A" changes a balance record in its copy and writes it to a file.
4. At this time, process "B" does not know that the last read file has been changed, and it also saves the original file copy. The process "B" then changes the same record of the "A" operation and writes the record to the file.
5. At this time, only the records changed by process "B" are saved in the file.
To avoid such a problem, we need to use a file lock to ensure the "serialization" of the operation ".
The following are two common file locks in Linux:
1. Collaborative lock
Collaborative Locks require collaboration between processes involved in the operation. Assume that process "A" acquires a write lock and begins to write content to the file. At this time, process "B" does not attempt to obtain a lock, it can still open the file and write content to the file. In this process, process "B" is a non-cooperative process. If process "B" tries to obtain a lock, the whole process is a cooperative process, which can ensure the "serialization" of the operation ".
Only when the process involved in the operation is collaborative, the collaborative lock can play a role. Collaborative locks are also called "unforced" locks.
2. Force lock
The process of force lock does not need to participate in the operation to maintain cooperation. It uses the kernel to check each open, read, and write operation to ensure that the file lock rules are not violated when these operations are called.
Difference between "collaborative lock" and "forced lock" in file locks