POSIX Mandatory Lock is a lock checked by Unix-like operating system to verify that the operation such as read
and write
does not interfere with a lock held by a process. It could be done by lockf()
#Unix System Call (imported from unistd.h
) which requires File Descriptor#, function used, and the length of the file. The locking starts from the current byte position of the file, and if the length is positive, then it will extend forward, otherwise it will extend backward. If length is 0, then the entire file is locked.
There are four functions could be used on lockf()
:
-
F_LOCK
sets an exclusive lock on the file, and blocks if it’s already locked until the lock is released. -
F_TLOCK
same asF_LOCK
but doesn’t block, and an error flag is set. -
F_ULOCK
releases the lock. -
F_TEST
tests whether the lock is set without setting a lock.
The flow of control could look like this:
int fd = open("hello.txt", ...);
if (lockf(fd, F_LOCK, 0) == -1) { // acquire lock
perror("lock");
}
// Do stuffs (criticial section)
if (lockf(fd, F_ULOCK, 0) == -1) { // relinguish lock
perror("lock");
}