Linux File lock: synchronization between processes tutorial, linux File lock
I. Scenarios
In addition to semaphores and shared memory (atomic operation) synchronization, multi-process synchronization can also be implemented using File locks.
II. Implementation
There are two methods in linux: flock () function and fcntl () function. The results are roughly the same.
Flock function:
Fd: file descriptor
Operation: LOCK_SH (adding a shared lock is equivalent to a read lock), LOCK_EX (adding an exclusive lock is equivalent to a write lock), LOCK_UN (removing the lock added to the file and unlocking ),
LOCK_NB, directly return results)
Fcntl function:
The file lock is:
Int fcntl (int fd, int cmd, struct flock *);
Struct flock definition:
Fd: file descriptor
Cmd: F_GETLK (get file lock information, query), F_SETLK (set file lock information, lock, unlock, no blocking by default), F_SETLKW (set file lock information, lock, unlock, default blocking)
Struct flock l_type: F_RDLCK (read lock), F_WRLCK (write lock), F_UNLCK (unlock)
Struct flock l_whence: Specifies the position of the file to be locked. When used, you can set the same position to achieve the locking effect. SEEK_SET (starting with the file), SEEK_CUR (current position of the file ), SEEK_END (end of the file)