Download flock-demo
#!/bin/sh
# Demo of Linux flock(1) advisory locking. This script will attempt
# to lock a file for 30 seconds, then release the lock. To see this
# work you need to start two copies of this script.
#
# This idiom is useful in administration scripts that read or write
# system configuration files.
#
# Written 10/2007 by Wayne Pollock, Tampa Florida USA
progname="${0##*/}[$$]"
if [ $# -eq 0 ]
then
printf "Usage: $progname <file>\n" >&2
exit 1
fi
file="$1"
if [ ! -r "$file" ]
then
printf "Error ($progname): \"$file\" is not readable!\n" >&2
exit 2
fi
printf "$progname: Attempting to obtain exclusive lock...\n"
(
flock -x 200
printf "$progname: Got lock!\n"
cat "$file" >/dev/null || printf "$progname: can't read \"$file\".\n"
sleep 12 # hold lock for a while
) 200>$file
printf "$progname: Released lock!\n"