bash 如何检查 flock 执行的命令的退出代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1964301/
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-17 21:30:22  来源:igfitidea点击:

How do I check the exit code of a command executed by flock?

bashcronexit-codefile-lockingflock

提问by Paul Accisano

Greetings all. I'm setting up a cron job to execute a bash script, and I'm worried that the next one may start before the previous one ends. A little googling reveals that a popular way to address this is the flockcommand, used in the following manner:

问候大家。我正在设置一个 cron 作业来执行一个 bash 脚本,我担心下一个可能会在前一个结束之前开始。稍微谷歌搜索显示,解决这个问题的一种流行方法是flock命令,以下列方式使用:

flock -n lockfile myscript.sh
if [ $? -eq 1 ]; then
    echo "Previous script is still running!  Can't execute!"
fi

This works great. However, what do I do if I want to check the exit code of myscript.sh? Whatever exit code it returns will be overwritten by flock's, so I have no way of knowing if it executed successfully or not.

这很好用。但是,如果我想检查 的退出代码该怎么办myscript.sh?它返回的任何退出代码都将被flock's覆盖,所以我无法知道它是否成功执行。

回答by Brian Campbell

It looks like you can use the alternate form of flock, flock <fd>, where <fd>is a file descriptor. If you put this into a subshell, and redirect that file descriptor to your lock file, then flock will wait until it can write to that file (or error out if it can't open it immediately and you've passed -n). You can then do everything in your subshell, including testing the return value of scripts you run:

它看起来像您可以使用的另一种形式flockflock <fd>其中<fd>是一个文件描述符。如果您将其放入子shell,并将该文件描述符重定向到您的锁定文件,那么 flock 将等待它可以写入该文件(如果无法立即打开它并且您已经通过了,则会出错-n)。然后,您可以在子 shell 中执行所有操作,包括测试您运行的脚本的返回值:

(
  if flock -n 200
  then
    myscript.sh
    echo $?
  fi
) 200>lockfile

回答by SiegeX

#!/bin/bash

if ! pgrep myscript.sh; then
  flock -n lockfile myscript.sh
fi

If I understand you right, you want to make sure 'myscript.sh' is not running before cron attempts to run your command again. Assuming that's right, we check to see if pgrep failed to find myscript.sh in the processes list and if so we run the flock command again.

如果我理解正确,那么在 cron 尝试再次运行您的命令之前,您需要确保 'myscript.sh' 没有运行。假设这是正确的,我们检查 pgrep 是否未能在进程列表中找到 myscript.sh,如果是,我们再次运行 flock 命令。

回答by Sami Kerola

Perhaps something like this would work for you.

也许这样的事情对你有用。

#!/bin/bash
RETVAL=0
lockfailed()
{
        echo "cannot flock"
        exit 1
}
(
        flock -w 2 42 || lockfailed
        false
        RETVAL=$?
        echo "original retval $RETVAL"
        exit $RETVAL
) 42>|/tmp/flocker
RETVAL=$?
echo "returned $RETVAL"
exit $RETVAL