In multi-process or multi-thread programming, file read and write operations may lead to data inconsistency. To avoid this situation, the C language provides a file locking mechanism to control access to the same file. This article will detail the file locking and file sharing mechanisms in C language and demonstrate them through code examples.
Basic Concepts of File Locking
What is File Locking?
File locking is a method used to control access to a specific resource (such as a file). When a process acquires a lock on a resource, other processes attempting to acquire that resource must wait until it is released. This prevents multiple processes from simultaneously modifying the same data, thereby ensuring data consistency and integrity.
File Sharing Modes
When using files, we typically encounter two main modes:
- Exclusive Mode: When a process acquires an exclusive lock, no other process can access that resource.
- Shared Mode: Multiple processes can read the same data simultaneously, but only one process can write to it.
Implementation in C Language
In C language, functions from the <span>fcntl.h</span> header file can be used to implement file locking and unlocking operations. Below, we will demonstrate how to use these functions through code examples.
Example Code
The following is a simple program that demonstrates how to apply exclusive and shared locks to a text file:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
void lock_file(int fd, int type) {
struct flock fl;
fl.l_type = type; // Lock type
fl.l_whence = SEEK_SET; // Start from the beginning
fl.l_start = 0; // Lock from the beginning
fl.l_len = 0; // Lock the entire area
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("Lock failed");
exit(EXIT_FAILURE);
}
}
void unlock_file(int fd) {
struct flock fl;
fl.l_type = F_UNLCK; // Unlock type
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("Unlock failed");
exit(EXIT_FAILURE);
}
}
int main() {
const char *filename = "test.txt";
int fd;
// Open or create test text
fd = open(filename, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("Open file failed");
return EXIT_FAILURE;
}
printf("Trying to acquire a write lock...\n");
// Acquire exclusive write lock
lock_file(fd, F_WRLCK);
printf("Write lock acquired! Writing to the file...\n");
const char *text_to_write = "Hello World!\n";
write(fd, text_to_write, strlen(text_to_write));
sleep(10); // Simulate holding write permission for a long time
printf("Releasing the write lock...\n");
unlock_file(fd);
close(fd);
return EXIT_SUCCESS;
}
Program Explanation
-
Open/Create Text: We first attempt to open a text file named
<span>test.txt</span>. If the text does not exist, it will be created automatically. -
Acquire Exclusive Write Lock: Call the
<span>lock_file</span>function and pass the<span>F_WRLCK</span>parameter to request an exclusive write lock on the document. During this time, if other programs attempt to acquire write permission for the same document, they will be blocked. -
Perform Write Operation: After successfully obtaining write permission, we add some content to the document and simulate holding this permission for 10 seconds to observe the effect.
-
Release Write Permission: Finally, we call the
<span>unlock_file</span>function to release the previously acquired exclusive rights, allowing other programs to access this document again.
Considerations
- In practical applications, ensure to handle errors appropriately, such as checking the success of each system call.
- Always unlock in a timely manner after use to avoid deadlocks.
- For large projects that require frequent read/write operations, consider more complex data structures and synchronization mechanisms, such as semaphores and condition variables, to improve performance and scalability.
Conclusion
This article introduced the importance and basic usage of file locking and sharing mechanisms in C language. Through simple and understandable code examples, we hope to help basic users understand how to safely manage concurrent access to data on disk in their projects. In actual development, please choose appropriate methods to protect your data security based on specific needs.