CodeBlanks Logo Icon CodeBlanks

flock

Learn file locking with flock.

What is flock?

flock is a simple BSD-origin file locking call. It locks the whole file; it does not support byte ranges. The flock(fd, operation) call is declared in <sys/file.h>. Three main operations exist: LOCK_SH shared, LOCK_EX exclusive, LOCK_UN unlock.

Shared locks are for reading, exclusive locks for writing. flock is advisory: cooperating processes honor the lock, but those that do not cooperate are not stopped. Combined with LOCK_NB, the call does not block if the lock cannot be acquired. Locks are tied to the file descriptor; close(fd) releases them automatically.

Open, lock, unlock, close

The typical flow is: open with open(path, O_CREAT | O_RDWR, 0644), lock with flock(fd, LOCK_EX), do the work, release with flock(fd, LOCK_UN), finally close(fd). Closing also releases the lock.

For testing you can print the state with printf("locked\n") and printf("unlocked\n"). The unlink(path) call removes the file so reruns leave no leftover. Error checking is done with if (flock(fd, LOCK_EX) == -1).

Practice Lock and unlock a file

Open the file with int fd = open("/tmp/cb_lock.txt", O_CREAT | O_RDWR, 0644);. Acquire the lock with flock(fd, LOCK_EX); and printf("locked\n");. Release with flock(fd, LOCK_UN); and printf("unlocked\n");. close(fd); and unlink("/tmp/cb_lock.txt");.

Starter code

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>

// Open file
// Take lock and print
// Release lock and print, then close and remove

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>

int main(void) {
    int fd = open("/tmp/cb_lock.txt", O_CREAT | O_RDWR, 0644);
    flock(fd, LOCK_EX);
    printf("locked\n");
    flock(fd, LOCK_UN);
    printf("unlocked\n");
    close(fd);
    unlink("/tmp/cb_lock.txt");
    return 0;
}

Expected output

locked
unlocked

Questions and answers

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

1 What does flock(fd, LOCK_EX) do?

  • Acquires exclusive lock Correct answer
  • Acquires shared lock
  • Releases lock
  • Deletes file

Explanation: LOCK_EX acquires an exclusive lock; used for writing.

2 flock call

Question
flock(fd, ____);
Answer
flock(fd, LOCK_EX);

Explanation: LOCK_EX acquires an exclusive lock.

3 Match flock constants

Term Meaning
LOCK_SH Shared
LOCK_EX Exclusive
LOCK_UN Unlocks
LOCK_NB Non-blocking

All lessons in Advanced