flock 命令

flock 命令,是Linux 的文件锁命令。可以通过一个锁文件,来控制在shell 中逻辑的互斥性。用法如下;

Usage:
 flock [options] <file|directory> <command> [command args]
 flock [options] <file|directory> -c <command>
 flock [options] <file descriptor number>

Options:
 -s  --shared             get a shared lock
 -x  --exclusive          get an exclusive lock (default)
 -u  --unlock             remove a lock
 -n  --nonblock           fail rather than wait
 -w  --timeout <secs>     wait for a limited amount of time
 -E  --conflict-exit-code <number>  exit code after conflict or timeout
 -o  --close              close file descriptor before running command
 -c  --command <command>  run a single command string through the shell

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see flock(1).

用它来实现我们上边说的“任务互斥”。可如下配置:

# old 
*/10 * * * * /bin/bash do_somethings_with_long_time.sh 

# new 
*/10 * * * * flock -xn /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

x 表示文件锁为互斥文件锁,这个参数可以省略,默认即为互斥文件锁。
n 表示当有任务执行时,直接退出,符合我们的逾期。
除了上边的功能,大家还可以实现排队等待、共享锁等功能。可如下配置:

# 排队执行  每个任务等待 20s,超时则退出
*/10 * * * * flock -w 20 /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

# 共享锁
*/10 * * * * flock -s /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

# 忽略锁,直接执行
*/10 * * * * flock -u /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

# 自定义退出码
*/10 * * * * flock -E 1 -w 20 /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

这里需要注意,在自定义退出码时,尽量使用1位的数字,当使用多位数字时,会出现不是自定义的其他返回码。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值