最後更新: 2017-12-20


  • flock
  • lock by create Dirtory




Install flock

# util-linux (Bultin)

# Normally “exec” in a shell script is used to turn over control of the script to some other program.
# open the file named in $lock for reading, and assign it file handle 200

exec 200>$lock


# locking
_scriptname=$(basename $0)
exec 200>$_pidfile
flock -xn 200 || { echo -n "another instance is running"; exit 1; }
echo $_pid
echo $_pid 1>&200

exclusive lock

Nobody can read it, because it's still being written, and she's blocking your view

shared locks

1. They all can read what is on it, together => Multiple shared locks can co-exist.
2. If one or more shared locks already exist, exclusive locks cannot be obtained.

Other software


distributed lock manager that can be used to synchronize shell commands


flock [options] <file|directory> -c <command>

flock [options] <file descriptor number>

-n, --nb, --nonblock
              Fail rather than wait if the lock cannot be immediately acquired.

-u, --unlock
              Drop  a  lock.   This  is  usually  not  required, since a lock is automatically
              dropped when the file is closed.

-s, --shared
              Obtain a shared lock, sometimes called a read lock.

-x, -e, --exclusive
              Obtain an exclusive lock, sometimes called a write lock. (Default)

-c, --command command
              Pass a single command, without arguments, to the shell with -c


flock -s /tmp -c cat


lock by create Dirtory


Those are two separate steps! That means it's not an atomic operation.

A simple way to get that is to create a lock directory

用 Directory 會消除 touch file 的問題

 * The syscall under mkdir is guarenteed to work atomicly in all cases

if mkdir /var/lock/mylock; then
  echo "Locking succeeded" >&2
  echo "Lock failed - exit" >&2
  exit 1