Linux 命令:flock - 对打开的文件加锁或解锁

先来看看flock -h 的用法:

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).

这个命令的使用场景是: 多个进程同时对一个文件有写入操作时,使用flock 加锁可以避免同时操作导致的文件数据混乱。当然不一定时文件写入操作,多个进程执行某一脚本时只允许一个进程执行也适用。类似于程序中的单例模式。

5/* * * * * sh /opt/scripts/update_mysql_data.sh p 这个定时任务中,脚本执行有可能超过5份钟,那么可能存在多个执行这个脚本的进程。
使用flock 后如下,就可避免5分钟还未执行完再执行的问题。

5/* * * * * flock -xn /tmp/update_mysql_data.lock -c 'sh /opt/scripts/update_mysql_data.sh'

另个这个锁文件 update_mysql_data.lock无需理会,锁使用完会释放掉,但文件存没什么关系。