C语言文件锁的实现

C文件锁的实现

  • 说明
    • 重复上锁
    • flock结构
  • 代码块,

说明

实现文件上锁的函数有flock和fcntl,其中flock用于对文件施加建议性锁,而fcntl不仅可以施加建议性锁,还可以施加强制锁。同时,fcntl还能对文件的某一记录进行上锁,也就是记录锁。

重复上锁

使用fcntl进行上锁后(此处为写入锁,读锁可重复上锁,写锁跟读锁跟写锁都不行),如果不解锁,本进程或者其他进程再次使用 fcntl(fd, F_SETLK, &Lock)命令访问同一文件则会告知目前此文件已经上锁加锁进程退出会自行解锁
int fcnt1(int fd, int cmd, struct flock *lock)

flock结构

flock 结构

struct flock      
{
short int l_type;     //锁定的状态  
short int l_whence; //决定l_start位置
off_t l_start;   //锁定区域的开头位置 
off_t l_len;   //锁定区域的长度,若为0,为全部
pid_t l_pid;   //锁定动作的进程
/*加锁整个文件,将 l_start = 0, l_whence = SEEK_SET,l_len = 0。*/
};

l_type 有三种状态:

F_RDLCK 建立一个供读取用的锁定 共享锁 readlock
F_WRLCK 建立一个供写入用的锁定 排他锁 writelock
F_UNLCK 删除之前建立的锁定 unlock

F_SETLK 设置文件锁定的状态。此时flcok 结构的l_type 值必须是F_RDLCK、F_WRLCK或F_UNLCK。如果无法建立锁定,则返回-1,错误代码为EACCES 或EAGAIN。

代码块,

此处代码为给.dmdbw_run_m10上写锁(排他锁),同时有两程序运行时lock_file(fd)会上锁失败,exit退出程序。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


```c
int lock_file(int fd)
{
	struct flock L1;
	L1.l_type = F_WRLCK;
	L1.l_start = 0;
	L1.l_whence = SEEK_SET;
	L1.l_len = 0;
	/* F_SETLK: 设置锁 */
	return (fcntl(fd, F_SETLK, &L1));
}

int main(int argc, char **argv)
{
	
	int fd;
	
	/* ORDWR:  以可读写方式打开文件
	 * OCREAT: 如文件不存在,则创建该文件 */
	fd = open(".dmdbw_run_m10", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
	if(fd < 0){  //打开失败
		exit(1);
	}
	
	if(lock_file(fd) == -1)  //-1上锁失败,无法锁定,存在冲突的写入锁
	{
	    printf("on  running\n");
		close(fd);
		exit(0);
	}
	
	printf("not running\n");
	getchar();
 
    close(fd);
    return 0;
}

如有错误,希望能留言指正,感谢。

你可能感兴趣的:(Linux开发相关,linux,c++,c语言)