bash flock:如果无法获得锁则退出 [英] bash flock: exit if can't acquire lock

查看:39
本文介绍了bash flock:如果无法获得锁则退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

#!/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.

我如何修改这个脚本,以便如果 flock 无法获取锁,它会终止脚本?我试过 -n 没有成功.

How do I alter this script so that if flock can't acquire the lock, it terminates the script? I've tried -n without success.

推荐答案

flock -n -e 200 || exit 1

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

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

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

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

这篇关于bash flock:如果无法获得锁则退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆