欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

记录锁

程序员文章站 2022-07-01 16:04:48
...

#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;
}


相关标签: 记录锁