bash flock: exit if can't acquire lock

跟風遠走 提交于 2019-11-28 07:33:46
flock -n -e 200 || exit 1

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.

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

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

exec 200<$0
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!