CodeBlanks Logo Icon CodeBlanks

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.

Practice 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");.

Starter code

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

// Open file
// Fill lock struct and set lock
// Print return, then unlock

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

fcntl: 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match fcntl parts

Term Meaning
F_SETLK Sets lock
F_WRLCK Write lock
F_UNLCK Unlocks
struct flock Lock struct

2 What does l_len = 0 mean in struct flock?

  • Zero-byte lock
  • Lock to end of file Correct answer
  • Returns error immediately
  • Only first byte

Explanation: l_len = 0 means lock to the end of file.

3 fcntl call

Question
fcntl(fd, ____, &fl);
Answer
fcntl(fd, F_SETLK, &fl);

Explanation: F_SETLK sets the lock; returns error on conflict.

All lessons in Advanced