Course contentsShow
← C
Lesson 1099 of 1,21915. Systems ProgrammingFree lesson

File locking with fcntl()

File locking with fcntl()

What you'll learn: How to use the fcntl() system call to prevent multiple processes from writing to the same file at the same time.

The "Talking Stick" for Files

Imagine a busy shared kitchen. If two people try to pour batter into the same waffle iron at once, you get a mess. To prevent this, you might establish a rule: you can only touch the waffle iron if you are holding the "kitchen spatula."

In systems programming, file locking is that spatula. When multiple processes (programs) run simultaneously, they might all try to write to a log file or a database at the exact same millisecond. Without coordination, the data becomes a scrambled "race condition" mess. fcntl() (File Control) allows a process to place a lock on a file, telling the OS: "I'm busy here; make everyone else wait."

Advisory Locking

By default, fcntl() provides advisory locking. This means the OS doesn't physically block a "rude" program from writing to the file. Instead, it’s like a "Wet Floor" sign. Polite programs check for the sign before entering; impolite ones might slip and cause a crash. For locking to work, every program accessing the file must agree to use fcntl().

Implementing a Write Lock

To lock a file, we use a struct flock. We tell the kernel we want an F_WRLCK (Write Lock), which is exclusive. If Process A holds a write lock, Process B will be blocked if it tries to grab one until Process A releases it.

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

int main() {
    int fd = open("database.txt", O_RDWR);
    
    struct flock lock;
    lock.l_type = F_WRLCK;    // Exclusive write lock
    lock.l_whence = SEEK_SET; // Start from beginning
    lock.l_start = 0;         // Offset 0
    lock.l_len = 0;           // Lock until end of file (0 means whole file)

    printf("Attempting to lock...\n");
    
    // F_SETLKW means "Set Lock and Wait"
    if (fcntl(fd, F_SETLKW, &lock) == -1) {
        perror("Locking failed");
        return 1;
    }

    printf("File locked! Performing safe write...\n");
    write(fd, "Data\n", 5);
    sleep(5); // Simulate work

    // Release the lock
    lock.l_type = F_UNLCK;
    fcntl(fd, F_SETLK, &lock);
    
    printf("File unlocked.\n");
    close(fd);
    return 0;
}

Key takeaway

Use fcntl() with F_SETLKW to ensure only one process at a time can modify a shared file, preventing data corruption through cooperative locking.