bash flock:如果无法获得锁则退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7057234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:35:13  来源:igfitidea点击:

bash flock: exit if can't acquire lock

bashconcurrencyflock

提问by Adam Matan

The following lock mechanism is used for preventing a cronjob from running concurrently:

以下锁定机制用于防止cron作业并发运行:

#!/bin/bash

echo "Before critical section"
(
    flock -e 200
    echo "In critical section"
    sleep 5
) 200>/tmp/blah.lockfile
echo "After critical section"

When running two instances together, the later waits until the first finishes, and then runs. This can cause backlogs of scripts waiting to run.

当两个实例一起运行时,后者会等待第一个实例完成,然后再运行。这可能会导致等待运行的脚本积压。

How do I alter this script so that if flockcan't acquire the lock, it terminates the script? I've tried -nwithout success.

如何更改此脚本,以便在flock无法获取锁定时终止脚本?我试过-n没有成功。

回答by John Zwinck

flock -n -e 200 || exit 1

flock -ntells you it failed by returning a failure code (something other than zero). You could instead do set -eat the top of your script to make it exit when it sees any unchecked error.

flock -n通过返回一个失败代码(非零)告诉你它失败了。您可以改为set -e在脚本顶部执行,以在它看到任何未检查的错误时退出。

Depending on your application, you might want to exit 0to indicate success when the lock can't be acquired.

根据您的应用程序,您可能希望在exit 0无法获取锁时指示成功。

回答by Yuri Aksenov

We use exclusive lock on the script file itself, $0is the name of command file.

我们对脚本文件本身使用排他锁,$0即命令文件的名称。

exec 200<##代码##
flock -n 200 || exit 1

The whole solution is in two lines of code. But the trick is to open $0 for reading and then obtain exclusive lock for it.

整个解决方案在两行代码中。但诀窍是打开 $0 进行读取,然后为其获取排他锁。