file locks

From Noah.org
Jump to navigationJump to search


The Linux command-line utility, flock can be used to work with locks.

To see locks us lsof and view /proc/locks.

This demonstrates locking a set of commands (echo and sleep) under filedescriptor #9 in a subshell.

( flock -n 9 || exit 1; echo "holding lock for 5 minutes..."; sleep 300) 9>/var/lock/my.lockfile

/proc/locks

Field #5 gives the PID of the process that obtained the lock. Note that this PID may be dead because the lock may be inherited by a parent or subprocess or thread. You may have to search around a bit. The third sub-field of field #6 gives the inode of the lock. This often must be used to find the PID of the process that currently holds the lock.

1: FLOCK  ADVISORY  WRITE 14547 00:11:4181978 0 EOF
2: POSIX  ADVISORY  WRITE 1063 00:0f:8265 0 EOF
3: FLOCK  ADVISORY  WRITE 987 ca:01:262934 0 EOF
4: FLOCK  ADVISORY  WRITE 987 ca:01:262780 0 EOF
5: POSIX  ADVISORY  WRITE 761 00:0f:7622 0 EOF
6: FLOCK  ADVISORY  WRITE 740 00:0f:7608 0 EOF

This command will produce a list of locks by searching for inodes, instead of PIDs. The first field is the PID of the process that originally obtained the lock; the second field is the /proc path to the PID that currently holds the lock (and the filedescriptor seen by that PID); the last field is the full path to the locked file. The first field PID often the same as the PID found in the second field, but not always.

while IFS=': ' read x x x x pid x x inode x; do sudo find -L /proc/*/fd -maxdepth 1 -inum "${inode}" -printf "${pid}: %p: " -exec readlink {} \; -quit; done < /proc/locks

This will give output similar to the following:

14547: /proc/14546/fd/9: /run/lock/my.lockfile                                                                                             
1063: /proc/1063/fd/6: /run/snort_eth0.pid.lck                                                                                             
987: /proc/987/fd/10: /var/lib/postfix/master.lock                                                                                         
987: /proc/987/fd/9: /var/spool/postfix/pid/master.pid                                                                                     
761: /proc/761/fd/3: /run/atd.pid                                                                                                          
740: /proc/762/fd/3: /run/crond.pid 

Note that the filedescriptor for my.lockfile is #9, which is what you would expect if you ran the flock -n 9 example. Note that the PID in this example does change. A subprocess was used to obtain the lock. The filedescriptor for the lock is actually owned by the parent process.