我的bash代码看起来喜欢:
set -e
(
flock -n 9
main $@
) 9>/var/lock/mylockfile
但是,如果无法在文件上锁定,目前却不会显示任何错误消息。有没有办法显示错误消息?
带有" set -e",您可以使用err信号。正如bash的人页面中所说的(描述带有选项的" set"命令" -e"):
"A trap on ERR, if set, is executed before the shell exits."
因此,您可以尝试以下操作:
set -e
(
trap 'echo flock failed.' ERR
flock -n 9
trap - ERR # reset ERR trap
main $@
) 9>/var/lock/mylockfile
manpage中的示例说:
(
flock -n 9 || exit 1
# ... commands executed under lock ...
) 9>/var/lock/mylockfile
即如果羊群失败,它将退出 - 为什么不使用它?如果要显示错误,可以尝试以下操作:
(
# paranoia: flock may fail with an exit code other than 1,
# eg if it can't be found in $PATH
if flock -n 9 ; then
do_stuff
else
show_error
fi
) 9>$lockfile
您应该检查flock -n
set -e
(
flock -n 9
if [ "$?" -eq 1 ] ; then
echo "could not lock"
exit 1
fi
main $@
) 9>/var/lock/mylockfile
我的解决方案:
lock="/tmp/name_of_lockfile.lck"
echo "Lockfile $lock"
exec 200>$lock
/usr/bin/flock -n --verbose 200 || exit 1
因此,运行成功时
Lockfile /tmp/name_of_lockfile.lck
flock: getting lock took 0.000006 seconds
而不是成功
Lockfile /tmp/name_of_lockfile.lck
flock: failed to get lock