文件锁定部分之文件锁(File lock)
①advisory locking②Mandatory Locking(通过内核强制检查文件的打开,读写操作)
要求:必须在文件系统上激活它,操作包括挂载mount文件系统。
cmd:
F_GETLK 得到锁
F_SETLK 设置锁
F_SETLKW 设置锁并等待返回
函数原型:
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
struct flock {
...
short l_type; /* Type of lock锁的类型:
/*F_RDLCK共享锁,
/*F_WRLCK独占锁,F_UNLCK分别
/*代表申请读锁,申请写锁,释放锁
short l_whence; /* How to interpret l_start:
/* SEEK_SET, SEEK_CUR, SEEK_END 锁
区
/*域开始地址的相对位置,类似于lseek中
/*SEEK_CUR, SEEK_END之一,
/* 分别代表相对文件起始位置,文件当前
位置,文件结束位置
off_t l_start; /* Starting offset for lock区域锁
开始的地址偏移量
off_t l_len; /* Number of bytes to lock锁的长
度,0表示锁到文件末尾
pid_t l_pid; /* PID of process blocking our lock
/*(F_GETLK only) 拥有锁的进程ID
...
};
实例用fcntl锁定一个文件以写模式(即独占模式)然后通过修改文件测试两种锁定模式
#include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/stat.h>
4 #include <sys/types.h>
5 #include <unistd.h>
6 #include <fcntl.h>
7
8 int main()
9 {
10 //open file
11 int fd = open("hello.txt",O_RDWR|O_CREAT,0666) ;
12 if(fd>0)
13 {
14 //local file
15 struct flock lock ;
16 lock.l_type = F_WRLCK ;
17 lock.l_whence = SEEK_SET ;
18 lock.l_start = 0 ;
19 lock.l_len = 0 ;
20 lock.l_pid = getpid() ;
21 int rd = fcntl(fd,F_SETLK,&lock) ;
22 printf("return value of lock:%d\n",rd) ;
23 while(1)
24 rd++ ;
25
26 }
27 }
运行结果
book@book-desktop:~/demo_lock$ gcc -o file_lock file_lock.c
book@book-desktop:~/demo_lock$ ls
file_lock file_lock.c hello.txt
book@book-desktop:~/demo_lock$ ./file_lock
return value of lock:0
标明加锁成功(独占锁)
实验用通道向hello.txt追加内容看能否成功?
book@book-desktop:~$ vim wanglei.c
book@book-desktop:~$ cd demo_lock/
book@book-desktop:~/demo_lock$ cat hello.txt
hello wanglei
book@book-desktop:~/demo_lock$ echo wanglei.c >>hello.txt
book@book-desktop:~/demo_lock$ cat hello.txt
hello wanglei
wanglei.c
book@book-desktop:~/demo_lock$
显示成功,因为默认情况下函数使用的是建议锁。强制锁需要重新挂载