Welcome to our comprehensive guide on C File Locking! In this lesson, we'll delve into the world of file handling and learn how to lock files in C. This guide is perfect for both beginners and intermediate learners. Let's get started!
File locking is a mechanism that ensures only one process can access a file at a time. It prevents multiple processes from reading and writing the same file simultaneously, thereby avoiding data inconsistency.
File locking is crucial in multi-user systems and real-world applications where multiple processes may need to access the same file. It prevents data corruption, data loss, and ensures data consistency.
In C, we have two functions for file locking: flock() and flockfile()/unlockfile().
flock() is a system call that locks or unlocks a file. It returns 0 on success and -1 on failure.
#include <sys/file.h>
int flock(int fd, int operation);fd is the file descriptor.operation can be one of the following:
LOCK_EX: Exclusive lock, only one process can lock the file.LOCK_SH: Shared lock, multiple processes can lock the file for reading.LOCK_UN: Unlock the file.flockfile() and unlockfile() are functions from <stdio.h> that work at the stream level. They lock or unlock the standard stream.
#include <stdio.h>
void flockfile(FILE *stream);
void unlockfile(FILE *stream);Let's write a simple program to lock a file.
#include <stdio.h>
#include <sys/file.h>
#include <fcntl.h>
int main() {
int fd = open("example.txt", O_RDWR | O_CREAT, 0644);
if (fd == -1) {
perror("Open failed");
return 1;
}
if (flock(fd, LOCK_EX) == -1) {
perror("Lock failed");
return 2;
}
printf("File is locked.\n");
// Perform operations here...
flock(fd, LOCK_UN);
close(fd);
return 0;
}In this example, we open a file example.txt, lock it exclusively, perform some operations, and then unlock it.
What does `flock()` return on success?