嵌入式应用开发学习笔记——高级文件IO
Fcntl文件锁
文件锁分为建议性锁和强制性锁
记录锁又可分为读取锁和写入锁
int fcntl(int fd, int cmd);
int fcntl(int fd, int cmd, long arg);
int fcntl(int fd, int cmd, struct flock *lock);
返回值:成功0,出错-1,错误原因存于errno
根据cmd参数的不同,fcntl函数有5种功能:
1)复制一个现有的描述符(cmd = F_DUPFD)
2)获得/设置文件描述符标记(cmd = F_GETFD或F_SETFD)
3)获得/设置文件状态标志(cmd = F_GETFL或F_SETFL)
4)获得/设置异步I/O所有权(cmd = F_GETOWN或F_SETOWN)
5)获得/设置记录锁(cmd = F_GETLK,F_SETLK或F_SETLKW)
flock的结构体定义
struct flock
{
short l_type; //F_RDLCK:读取锁(共享锁) F_WRLCK:写入锁(排斥锁) F_UNLCK:解锁
off_t l_start; //相对位移量(字节)
short l_whence; //SEEK_SET:文件开头+l_start为新读写位置
//SEEK_CUR:目前读写位置+l_start为新读写位置
//SEEK_END:文件结尾+l_start为新读写位置
off_t l_len; //加锁区域的长度
pid_t l_pid;
}
例程:
lock_set.c文件
#include <sys/types.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <errno.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include "lock_set.h"
8
9 int lock_set(int fd, int type)
10 {
11 struct flock lock;
12 lock.l_whence = SEEK_SET;
13 lock.l_start = 0;
14 lock.l_len = 0;
15 //lock.l_type = type;
16 lock.l_pid = -1;
17
18 fcntl(fd, F_GETLK, &lock);
19 if(lock.l_type != F_UNLCK)
20 {
21 if(lock.l_type == F_RDLCK)
22 {
23 printf("Read lock already set by %d\n", lock.l_pid);
24 }
25 else if(lock.l_type == F_WRLCK)
26 {
27 printf("Write lock already set by %d\n", lock.l_pid);
28 }
29 }
30
31 lock.l_type = type;
32
33 if(fcntl(fd, F_SETLKW, &lock) < 0)
34 {
35 perror("fcntl lock failed");
36 exit(1);
37 }
38 switch(lock.l_type)
39 {
40 case F_RDLCK:
41 printf("Read lock set by %d\n", getpid());
42 break;
43 case F_WRLCK:
44 printf("Write lock set by %d\n", getpid());
45 break;
46 case F_UNLCK:
47 printf("Release lock set by %d\n", getpid());
48 break;
49 default:
50 break;
51
52 }
53
54 }
fcntl_rd.c文件
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4 #include <fcntl.h>
5
6 #include "lock_set.h"
7
8 int main(void)
9 {
10 int fd;
11 fd = open("test.txt", O_RDONLY);
12 if(fd < 0)
13 {
14 perror("open");
15 exit(1);
16 }
17 lock_set(fd, F_RDLCK);
18 getchar();
19
20 lock_set(fd, F_UNLCK);
21 getchar();
22
23 close(fd);
24 return 0;
25 }
fcntl_wr.c文件
#include <stdio.h>
2 #include <stdlib.h>
3 #include <fcntl.h>
4 #include <string.h>
5 #include <errno.h>
6 #include "lock_set.h"
7
8 int main(void)
9 {
10 int fd;
11 fd = open("test.txt", O_RDWR);
12 if(fd < 0)
13 {
14 perror("open");
15 exit(1);
16 }
17 lock_set(fd, F_WRLCK);
18 getchar();
19 lock_set(fd, F_UNLCK);
20 getchar();
21
22 close(fd);
23 return 0;
24 }