linux使用flock文件锁

使用linux flock 文件锁实现任务锁定,解决冲突

格式:

flock [-sxun][-w #] fd#

flock [-sxon][-w #] file [-c] command

flock --help
flock (util-linux-ng 2.17.2)
Usage: flock [-sxun][-w #] fd#
flock [-sxon][-w #] file [-c] command...
flock [-sxon][-w #] directory [-c] command...
-s --shared Get a shared lock
-x --exclusive Get an exclusive lock
-u --unlock Remove a lock
-n --nonblock Fail rather than wait
-w --timeout Wait for a limited amount of time
-o --close Close file descriptor before running command
-c --command Run a single command string through the shell
-h --help Display this text
-V --version Display version

-s, --shared: 获得一个共享锁
-x, --exclusive: 获得一个独占锁
-u, --unlock: 移除一个锁,通常是不需要的,脚本执行完会自动丢弃锁
-n, --nonblock: 如果没有立即获得锁,直接失败而不是等待
-w, --timeout: 如果没有立即获得锁,等待指定时间
-o, --close: 在运行命令前关闭文件的描述符号。用于如果命令产生子进程时会不受锁的管控
-c, --command: 在shell中运行一个单独的命令
-h, --help 显示帮助
-V, --version: 显示版本

example:  crontab运用flock防止重复执行

touch /tmp/my.lock  # 创建一个锁文件

*/30  * * * * loki flock -xn /tmp/my.lock -c 'sh 你的脚本文件.sh'   # -n 为非阻塞模式,会等一直等待程序执行完毕后再执行

解决问题:

防止某个脚本没有执行完毕的同时又另外的脚本再次启动

参考资料:

https://blog.csdn.net/fdipzone/article/details/38284009/

https://www.cnblogs.com/wangxusummer/p/4933492.html

猜你喜欢

转载自www.cnblogs.com/Cong0ks/p/9299097.html