C
fcntl
Learn advanced file locking with fcntl.
fcntl locks
fcntl is the POSIX byte-range locking tool. The struct flock structure defines the lock type (l_type), start (l_start), relative position (l_whence) and length (l_len). l_len = 0 locks to the end of file.
fcntl(fd, F_SETLK, &fl) acquires a lock; it returns -1 on conflict. F_SETLKW is the waiting version. F_RDLCK is a read lock, F_WRLCK a write lock, F_UNLCK unlocks. Unlike flock, fcntl is per-process; the same process can reacquire.
Filling struct flock
Before acquiring a lock you must fill struct flock fl;. Setting fl.l_type = F_WRLCK;, fl.l_whence = SEEK_SET;, fl.l_start = 0; and fl.l_len = 0; defines an exclusive lock from file start to end.
The int r = fcntl(fd, F_SETLK, &fl); call acquires the lock; it returns 0 on success, -1 on conflict. For testing, print the return: printf("fcntl: %d\n", r);. To unlock, set fl.l_type = F_UNLCK; and repeat the call. close(fd) releases all locks automatically.
Exercise Acquire a lock with fcntl
Open the file with int fd = open("/tmp/cb_fcntl.txt", O_CREAT | O_RDWR, 0644);. Declare struct flock fl;; set fl.l_type = F_WRLCK;, fl.l_whence = SEEK_SET;, fl.l_start = 0;, fl.l_len = 0;. Call int r = fcntl(fd, F_SETLK, &fl); and printf("fcntl: %d\n", r);. Set fl.l_type = F_UNLCK; and call fcntl(fd, F_SETLK, &fl); again. close(fd); and unlink("/tmp/cb_fcntl.txt");.
Show example solution
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
int fd = open("/tmp/cb_fcntl.txt", O_CREAT | O_RDWR, 0644);
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
int r = fcntl(fd, F_SETLK, &fl);
printf("fcntl: %d\n", r);
fl.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &fl);
close(fd);
unlink("/tmp/cb_fcntl.txt");
return 0;
}
Test yourself
-
Match fcntl parts
- F_SETLK
- Sets lock
- F_WRLCK
- Write lock
- F_UNLCK
- Unlocks
- struct flock
- Lock struct
-
What does l_len = 0 mean in struct flock?
- Zero-byte lock
- Lock to end of file
- Returns error immediately
- Only first byte
Show answer
Lock to end of file — l_len = 0 means lock to the end of file.
-
fcntl call
fcntl(fd, ____, &fl);
Show answer
fcntl(fd, F_SETLK, &fl);
Next lesson: Lock types