起语:
版权声明: 腾讯课堂->奇牛学院.
我只是用来方便学习 && 复习!!! 我只是一个学习者, 内功有限, 大家看到谨慎参考!!! 我建议多看官方文档.
文件锁
1)并发对文件I/O操作的影响
- 解决办法?
2)文件锁
- 用法: man 2 fentl
- 文件锁的表示 struct flock
struct flock结构体说明
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 */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
pid_t l_pid; /* PID of process blocking our lock
(F_GETLK only) */
...
};
l_type: 第一个成员是加锁的类型: 只读锁,读写锁,或是解锁。
l_start 和 l_whence:用来指明加锁部分的开始位置。
l_len:是加锁的长度。
l_pid: 是加锁进程的进程id.
演示代码
1demo_文件锁1.c
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#define TOTAL 10
int main(int argc, char *argv[])
{
const char *TEXT = "This is a test.\n";
const char *filename = "./write.txt";
int fd = -1;
int i = 0;
fd = open(filename, O_RDWR|O_TRUNC|O_CREAT);
if (fd