对 Linux 中的只读文件设置独占锁

Placing exclusive lock on read-only files in Linux

假设:

需求:一个文件只能被一个进程读取。完成后,文件将被删除或移动到其他位置。所有文件都不会written/edited。例如,我有 5 个文件和 2 个进程 运行 并行。我需要确保进程 1 将读取文件 1、3 和 5 并对其执行一些操作。进程 2 将读取文件 2 和 4 并对其执行一些操作。这意味着计算分布是在文件级别完成的。我们不会在文件中分发计算。

在Linux上,有两个函数可以放置独占锁:flock and fcntl。他们互换工作并尊重其他人放置的锁。问题是这两个函数都需要 "write" 权限。

Boost 库还具有 boost::interprocess::file_lock::try_lock() 功能。它与上述两个功能的作用相同。它还需要 "write" 权限。

是否有任何其他方法可以对我没有 "write" 权限的文件设置排他锁?

Any access (read or write) will suffice for a Linux flock syscall to place a lock on file, unlike fcntl lock which requires 读取锁定的读取权限和写入锁定的写入权限。

您可能正在使用在 fcntl 之上模拟 flock 的 libc。要得到你需要的,直接通过syscall:

调用系统调用
#include <sys/syscall.h>
#include <unistd.h>

// from include/uapi/asm-generic/fcntl.h
#define SYS_LOCK_SH 1
#define SYS_LOCK_EX 2
#define SYS_LOCK_UN 8

static int sys_flock(int fd, int op)
{
    return (int) syscall(SYS_flock, fd, op);
}

因此,以下程序必须成功:

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>

#define SYS_LOCK_EX 2

static long sys_flock(int fd, int flags)
{
    return (int) syscall(SYS_flock, fd, flags);
}

int main(void)
{
    int fd = open("/etc/hosts", O_RDONLY);
    int ret = sys_flock(fd, SYS_LOCK_EX);

    if (ret) {
        errno = -ret;
        perror("flock");
        return 1;
    }
}