共享锁(Shared Lock):
排他锁(Exclusive Lock):
共享锁的优势:
排他锁的优势:
共享锁的应用场景:
排他锁的应用场景:
常见问题:
解决方法:
# 使用fcntl系统调用实现共享锁和排他锁
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd = open("example.txt", O_RDWR);
if (fd == -1) {
perror("open");
return 1;
}
// 获取共享锁
struct flock fl;
fl.l_type = F_RDLCK; // 共享锁
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
close(fd);
return 1;
}
// 读取文件内容
char buffer[100];
read(fd, buffer, sizeof(buffer));
printf("Read: %s\n", buffer);
// 释放共享锁
fl.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
close(fd);
return 1;
}
// 获取排他锁
fl.l_type = F_WRLCK; // 排他锁
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
close(fd);
return 1;
}
// 写入文件内容
const char *new_content = "New content";
write(fd, new_content, strlen(new_content));
// 释放排他锁
fl.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
close(fd);
return 1;
}
close(fd);
return 0;
}
领取专属 10元无门槛券
手把手带您无忧上云