Article Title: Key Points of Linux File lock. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
File lock is one of the most common inter-process synchronization mechanisms in Linux. Compared with sysv semaphores, file locks are easier to use (the trouble of sysv semaphores lies in its key Acquisition Mechanism ).
APUE provides a detailed description of the file lock. Note the following points. For the original article, see section 14.3 of APUE2:
1. The file lock (file_lock) is bound to the file (specifically the file inode) and process. The file_lock structure of the file in the Linux implementation is mounted to the inode structure corresponding to the file, the file_lock structure contains the pid of the process to which the lock belongs. this implementation method has two consequences:
A. When a process exits, all file locks belonging to the process are released.
B. When any fd or file to which the lock process belongs is disabled, the lock is released. This is because the file_lock structure is mounted on inode rather than fd or file (the next stop of fd in the kernel structure), so it is impossible to distinguish the fd or file corresponding to the file lock. Note that two examples are listed on APUE. The first one is fd disabled, and the second one is file disabled. Both cases will cause lock release:
Fd1 = open (pathname ,...); Read_lock (fd1 ,...); Fd2 = dup (fd1 ); Close (fd2 );
Fd1 = open (pathname ,...); Read_lock (fd1 ,...); Fd2 = open (pathname ,...) Close (fd2 ); |
APUE has a FreeBSD file lock implementation diagram to help you understand the above content, which is also applicable to Linux.
2. After fork (), the child process does not inherit the lock of the parent process. It is easy to understand that the lock is used by the process to execute mutex and other tasks. If it fails, it will become messy.
3. exec () can inherit the lock. It depends on whether the lock fd is closed (close-on-exec) after exec (). This is because the process before and after exec () is still one.