记录锁



#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#define read_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLK, F_RDLCK, offset, whence, len)
#define read_lockw(fd, offset, whence, len) \
lock_reg(fd, F_SETLKW, F_RDLCK, offset, whence, len)
#define write_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLK, F_WRLCK, offset, whence, len)
#define write_lockw(fd, offset, whence, len) \
lock_reg(fd, F_SETLKW, F_WRLCK, offset, whence, len)
#define un_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLK, F_UNLCK, offset, whence, len)
#define is_read_lock(fd, offset, whence, len) \
!lock_test(fd, F_RDLCK, offset, whence, len)
#define is_write_lock(fd, offset, whence, len) \
!lock_test(fd, F_WRLCK, offset, whence, len)
/**
* @brief 记录上锁或解锁
* @param fd 文件描述符
* @param cmd F_SETLK, F_SETLKW, F_GETLK
* @param type F_RDLCK, F_WRLCK, F_UNLCK
* @param offset bytes offset, relative to whence
* @param whence SEEK_SET, SEEK_CUR, SEEK_END
* @param len bytes to lock, 0 means to EOF
* @return 0 on success, -1 when failed
*/
int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
return fcntl(fd, cmd, &lock);
}

/**
* @brief 测试记录是否上锁
* @param fd 文件描述符
* @param cmd F_SETLK, F_SETLKW, F_GETLK
* @param type F_RDLCK, F_WRLCK, F_UNLCK
* @param offset bytes offset, relative to whence
* @param whence SEEK_SET, SEEK_CUR, SEEK_END
* @param len bytes to lock, 0 means to EOF
* @return error return -1; locked return lock pid; unlocked return 0;
*/
int lock_test(int fd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
if (-1 == fcntl(fd, F_GETLK, &lock)) {
return -1;
}
if (lock.l_type == F_UNLCK)
return 0;
return lock.l_pid;
}

int main(int argc, char **argv)
{
int fd;
int ret;

fd = open("test.lock", O_RDWR | O_CREAT);
if (-1 == fd) {
perror("error to open");
return -1;
}

ret = write_lock(fd, 0, SEEK_SET, 0);
if (-1 == ret) {
perror("error while write lock");
close(fd);
return -1;
}
printf("Success to write lock\n");
pause();

close(fd);

return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值