Linux数据管理学习:文件锁定
发布时间:2016-10-31 01:27:29 所属栏目:Linux 来源:网络整理
导读:一、什么是文件锁定 对于锁这个字,大家一定不会陌生,因为我们生活中就存在着大量的锁,它们各个方面发挥着它的作用,现在世界中的锁的功能都可归结为一句话,
|
5、例子 看了这么多的说明,可能你已经很乱了,就用下面的例子来整清你的思想吧。 源文件名为filelock2.c,用于创建数据文件,并将文件区域加锁,代码如下:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
const char *test_file = "test_lock.txt";
int file_desc = -1;
int byte_count = 0;
char *byte_to_write = "A";
struct flock region_1;
struct flock region_2;
int res = 0;
//打开一个文件描述符
file_desc = open(test_file, O_RDWR|O_CREAT, 0666);
if(!file_desc)
{
fprintf(stderr, "Unable to open %s for read/writen", test_file);
exit(EXIT_FAILURE);
}
//给文件添加100个‘A’字符的数据
for(byte_count = 0; byte_count < 100; ++byte_count)
{
write(file_desc, byte_to_write, 1);
}
//在文件的第10~29字节设置读锁(共享锁)
region_1.l_type = F_RDLCK;
region_1.l_whence = SEEK_SET;
region_1.l_start = 10;
region_1.l_len = 20;
//在文件的40~49字节设置写锁(独占锁)
region_2.l_type = F_WRLCK;
region_2.l_whence = SEEK_SET;
region_2.l_start = 40;
region_2.l_len = 10;
printf("Process %d locking filen", getpid());
//锁定文件
res = fcntl(file_desc, F_SETLK, ion_1);
if(res == -1)
{
fprintf(stderr, "Failed to lock region 1n");
}
res = fcntl(file_desc, F_SETLK, ion_2);
if(res == -1)
{
fprintf(stderr, "Failed to lock region 2n");
}
//让程序休眠一分钟,用于测试
sleep(60);
printf("Process %d closing filen", getpid());
close(file_desc);
exit(EXIT_SUCCESS);
}
查看本栏目更多精彩内容:http://www.bianceng.cn/OS/Linux/ (编辑:佛山站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

