This example demonstrates usage of lockf
function (POSIX XSI).
Notes:
len
argument and position set with lseek
function).fcntl
and lockf
locks is unspecified. On Linux, lockf
is a wrapper for POSIX record locks.#include <stdlib.h> /* for exit() */
#include <stdio.h> /* for perror() */
#include <unistd.h> /* for lockf(), lseek() */
#include <fcntl.h> /* for open() */
int main(int argc, char **argv) {
/* open file
* we need O_RDWR for lockf */
int fd = open(argv[1], O_RDWR);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
/* set current position to byte 10 */
if (lseek(fd, 10, SEEK_SET) == -1) {
perror("lseek");
exit(EXIT_FAILURE);
}
/* acquire exclusive lock for bytes in range [10; 15)
* F_LOCK specifies blocking mode */
if (lockf(fd, F_LOCK, 5) == -1) {
perror("lockf(LOCK)");
exit(EXIT_FAILURE);
}
/* release lock for bytes in range [10; 15) */
if (lockf(fd, F_ULOCK, 5) == -1) {
perror("lockf(ULOCK)");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}