In Linux, the functions used to implement File locks include lock and fcntl, where lock is used to apply a commit lock to the file, while fcntl can not only apply a mandatory lock, but also apply a commit lock. At the same time, fcntl can lock a file record, that is, record lock.
Record locks are divided into read locks and write locks. Read locks are also called shared locks. It enables multiple processes to create read locks in the unified part of the file. The write lock is also called the exclusion lock. At any time, only one process establishes a write lock on a part of the file. Of course, the unified part of the file cannot create both read locks and write locks.
A forced lock is a lock executed by the kernel. When a file is locked for write operations, the kernel will prevent any other files from performing read/write operations on it.
Int fcntl (int fd, int cmd, struct flock * lock)
Fd: file descriptor
Cmd:
Lock: The structure is flock, and the specific status of the record lock is set.
Returned value: Success: 0
-1, error.
Struck flock {
Short l_type;
Off_t l_start;
Short l_whence;
Off_t l_len;
Pid_t l_pid;
}
L_type: F_RDLCK F_WRLCK F_UNLCK
L_stat: relative displacement
Rochelle whence: SEEK_SET SEEK_END SEEK_CUR
L_len: the length of the lock area;
To lock the entire file, the general method is to describe l_start to 0, and Rochelle whence to SEEK_SET.l_len to 0.