C
Lock types
Learn the difference between shared and exclusive locks.
Shared and exclusive
There are two main lock types. A shared lock (LOCK_SH or F_RDLCK) allows multiple readers; it can be taken when no writer holds the lock. An exclusive lock (LOCK_EX or F_WRLCK) grants single ownership; it can be taken only when no other lock exists.
You take a shared lock for reading and an exclusive lock for writing. This rule prevents readers from seeing inconsistent data. If the same process reads and writes, an exclusive lock suffices. You can convert locks: first take LOCK_SH, then upgrade to LOCK_EX; releasing with LOCK_UN in between is the safest path.
Lock upgrade
Sometimes we first read, then write. We may want to take LOCK_SH first and then upgrade to LOCK_EX. Direct conversion may block on some systems; the safest path is to release with LOCK_UN and then take LOCK_EX.
For testing, you can take and release both lock types in sequence: flock(fd, LOCK_SH); printf("shared\n"); flock(fd, LOCK_UN); flock(fd, LOCK_EX); printf("exclusive\n"); flock(fd, LOCK_UN);. This clearly shows how shared and exclusive locks behave.
Exercise Try both lock types
Open the file with int fd = open("/tmp/cb_types.txt", O_CREAT | O_RDWR, 0644);. Call flock(fd, LOCK_SH);, printf("shared\n");, flock(fd, LOCK_UN);. Then flock(fd, LOCK_EX);, printf("exclusive\n");, flock(fd, LOCK_UN);. close(fd); and unlink("/tmp/cb_types.txt");.
Show example solution
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
int main(void) {
int fd = open("/tmp/cb_types.txt", O_CREAT | O_RDWR, 0644);
flock(fd, LOCK_SH);
printf("shared\n");
flock(fd, LOCK_UN);
flock(fd, LOCK_EX);
printf("exclusive\n");
flock(fd, LOCK_UN);
close(fd);
unlink("/tmp/cb_types.txt");
return 0;
}
Test yourself
-
Shared lock
flock(fd, ____);
Show answer
flock(fd, LOCK_SH);
-
Match lock types
- LOCK_SH
- Many readers
- LOCK_EX
- Single writer
- F_RDLCK
- Read lock
- F_WRLCK
- Write lock
-
Which lock should be taken when writing?
- Shared lock
- No lock access
- Exclusive lock
- Read lock only
Show answer
Exclusive lock — Writing requires an exclusive lock (LOCK_EX).
Next lesson: Deadlock