linux - 语法上更简单的 flock 调用

标签 linux bash locking flock

我使用 flock 是因为我们有 N 个同时启动的进程,它们都需要对文件的读取权限。如果该文件不存在,我们需要创建它,但只有一个进程可以这样做,否则它们会互相覆盖。

如何使用 Linux 的 flock 做到这一点的正常示例是这样的:

(
    flock -n 9 || exit 1
    if [ ! -f file.txt ]; then
        echo 'Simulate the file creation' > file.txt
    fi
) 9>/var/lock/mylockfile

但是,这读起来很困惑,特别是如果您不熟悉子 shell 和文件描述符。我想知道是否可以手动锁定和解锁文件:

flock --exclusive file.txt

if [ ! -f file.txt ]; then
    echo 'Simulate the file creation' > file.txt
fi

flock --unlock file.txt

如果没有,是否有一些类似的方法来使用 flock,尽可能可读,避免子 shell、exec 等?

最佳答案

我建议您遵循手册页中的习惯用法,并向读者提供手册页的 URL 作为评论。从某种意义上说,我建议对您的代码进行此更改:

# flock usage:  Please see https://stackoverflow.com/questions/56955601/syntactically-simpler-flock-invocation
# Or see flock third form usage here:  http://man7.org/linux/man-pages/man1/flock.1.html

(
    flock -n 9 || exit 1
    if [ ! -f file.txt ]; then
        echo 'Simulate the file creation' > file.txt
    fi
) 9>/var/lock/mylockfile

也就是说,我认为您的逻辑很好,但我会选择使用您正在创建的文件以外的另一个锁定文件。

下面是我将如何尝试您的方法:

flock --exclusive /var/log/mylockfile

if [ ! -f file.txt ]; then
    echo 'Simulate the file creation' > file.txt
fi

flock --unlock /var/log/mylockfile

完全披露:我自己没有尝试过,也没有使用 flock。我确实同意您的方法比联机帮助页提供的第三个用法更直观、更易于阅读。您可能会考虑在开始并行流程之前只创建文件(但我敢肯定,由于您的特殊情况,已经考虑并放弃了)。

关于linux - 语法上更简单的 flock 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56955601/

相关文章:

java - 在 Linux 上的 Eclipse RCP 应用程序中加载 native 库

linux - 无法解压文件

Python threading.Condition.notify_all() 不触发下一个线程

c++ - boost::lock_guard 分配、构造函数和析构函数开销

linux - 从 bash 启动 apachectl

c# - 为什么在 WinForms (.NET) 中隐藏拥有的窗口切换应用程序?

python - 如何使用 Python 脚本退出 Linux 终端?

linux - bash输出到文件

bash - 如何将 grep 的值分配给变量并与字符串连接?

locking - 对 DBMS 锁定的说明