C
Summary - File locking
Combine flock and fcntl to write a lock manager.
File locking summary
You learned two file locking tools: flock simple and whole-file, fcntl byte-range and POSIX standard. Both are advisory; cooperating processes honor locks.
Lock types: shared (read) and exclusive (write). Deadlock arises from circular wait; it is prevented by lock ordering. Automatic cleanup is ensured with close and atexit. In this summary we will combine flock and fcntl into a lock manager.
Exercise Write a lock manager
Open the file with int fd = open("/tmp/cb_mgr.txt", O_CREAT | O_RDWR, 0644);. Take a flock lock with flock(fd, LOCK_EX);. Declare struct flock fl;; set fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; and call fcntl(fd, F_SETLK, &fl);. printf("lock manager\n");. flock(fd, LOCK_UN);, fl.l_type = F_UNLCK;, fcntl(fd, F_SETLK, &fl);. close(fd); and unlink("/tmp/cb_mgr.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_mgr.txt", O_CREAT | O_RDWR, 0644);
flock(fd, LOCK_EX);
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fcntl(fd, F_SETLK, &fl);
printf("lock manager\n");
flock(fd, LOCK_UN);
fl.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &fl);
close(fd);
unlink("/tmp/cb_mgr.txt");
return 0;
}
Next steps
You completed file locking. These foundations are the core of database engines, configuration files and log rotation. flock is used for simple scenarios, fcntl for fine-grained range control.
Next topics: terminal I/O for interactive apps, dynamic loading for plugin systems and cryptography for security. All combine with solid lock management.
Test yourself
-
When is fcntl preferred over flock?
- When whole-file lock is needed
- When byte-range lock is needed
- When only shared lock is needed
- When no lock is needed
Show answer
When byte-range lock is needed — fcntl gives byte-range locks; flock locks the whole file.
-
Match locking concepts
- flock
- Whole file
- fcntl
- Byte range
- LOCK_EX
- Exclusive
- atexit
- Exit cleanup
Next lesson: termios