How to operate a file that has been shared, that is, how to ensure the correctness of file data when multiple processes operate on the same file at the same time. Linux usually uses File Locking to avoid competition for shared resources.
File locks include the commit locks and mandatory locks. Built upon, as the name implies, is relatively gentle. When you lock a file, the system checks whether the lock exists and respects the existing lock. In general, neither the kernel nor the system uses the recommended lock. A mandatory lock is a lock executed by the kernel. When a file is locked for write operations, the kernel will prevent other processes from performing read/write operations on it. The adoption of mandatory locks has a great impact on performance. Each read/write operation must check whether a lock exists.
You can use the lockf () and fcntl () functions to lock files in Linux. The former applies the locks to files, and the latter applies the locks to files. In addition, fcntl can lock a file record.
Fcntl format:
Int fcntl (int fd, int cmd, struct flock * Lock );
FD is the file descriptor, CMD is some command parameters, and flcok struct is used to set the specific status of the record lock.
Fcntl () operates on opened file descriptors and can execute different tasks according to different command parameters. Several Command Options for file lock are as follows:
F_getlk determines whether to lock files based on the lock parameter value.
F_setlk: sets the file lock of the lock parameter value.
F_setlkw this isF_getlkWhen the lock cannot be obtained, it enters the sleep state.
The flock struct is defined as follows:
Struct flock {
Short l_type;
Off_t l_start;
Short l_whence;
Off_t l_len;
Pid_t l_pid;
}
Rochelle type has three options:
F_rdlck: Shared lock, read-only
F_wrlck: Exclusive lock (write operation lock)
F_unlck: Unlock
L_start indicates the relative displacement.
L_whence must be one of the following values (defined in unistd. h ):
Seek_set: File start location
Seek_cur: Current file location
Seek_end: Position at the end of the file
Length of the l_len lock
Rochelle PID process ID of the current file operation
The following is a simple example.
Running result:
Read can be shared.
Write example:
Running result:
If you write at the same time, the competition occurs. The latter cannot write the file. Only when the current lock is unlocked can the file be written in the future.
Use System Call fcntl () to lock files