Summary - File locking
- C course
- Advanced
- Lesson 42/83
- 5 min
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.
Practice 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");.
Starter code
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
// Open file and take lock
// Set second lock with lock struct
// Print, release, close and remove
int main(void) {
return 0;
}Sample 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;
}Expected output
lock manager
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.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is fcntl preferred over flock?
- When whole-file lock is needed
- When byte-range lock is needed Correct answer
- When only shared lock is needed
- When no lock is needed
Explanation: fcntl gives byte-range locks; flock locks the whole file.
2 Match locking concepts
| Term | Meaning |
|---|---|
flock |
Whole file |
fcntl |
Byte range |
LOCK_EX |
Exclusive |
atexit |
Exit cleanup |