文件锁
www.zhaoch.top > 编程 > c_cpp
文件锁
可以锁整个文件或者一部分
TODO测试代码
stdio提供了一个简单的接口
#include <stdio.h>
void flockfile(FILE *filehandle);
int ftrylockfile(FILE *filehandle);
void funlockfile(FILE *filehandle);
通过fcntl和struct flock
通过fcntl和struct flock可以实现更复杂的功能,比如只锁住某个区间
以下是nginx的相关代码
ngx_err_t
ngx_trylock_fd(ngx_fd_t fd)
{
struct flock fl;
ngx_memzero(&fl, sizeof(struct flock));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &fl) == -1) {
return ngx_errno;
}
return 0;
}
ngx_err_t
ngx_lock_fd(ngx_fd_t fd)
{
struct flock fl;
ngx_memzero(&fl, sizeof(struct flock));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLKW, &fl) == -1) {
return ngx_errno;
}
return 0;
}
ngx_err_t
ngx_unlock_fd(ngx_fd_t fd)
{
struct flock fl;
ngx_memzero(&fl, sizeof(struct flock));
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &fl) == -1) {
return ngx_errno;
}
return 0;
}
https://blog.csdn.net/wallwind/article/details/7816221 https://www.cnblogs.com/kex1n/p/7100107.html
The End
- My github location
- View Source of this website GhostZch.github.io
- Commit issues to discuss with me and others