#!/bin/bash # lockfile.sh [-p pid] [-t timeout] lockfile_name # -p pid calling process PID. This value will be # writen into created lockfile. Default is 0 # -t timeout polling interval in seconds when checking # if file already exists. Default is 1 # lockfile_name name of created lock file LPID=0 LSLEEP=1 LFILE= # options parsing # -- all except last while test $# -ge 2 do LASTOPT="$1" shift case "$LASTOPT" in -p) LPID="$1" shift ;; -t) LSLEEP="$1" shift ;; esac done # -- last option - the name of lockfile test $# -ge 1 && LFILE="$1" LFTMP=".$LFILE-$$" function cleanup { rm -f "$LFTMP" } trap cleanup EXIT # Create read only temp file rm -f "$LFTMP" umask 333 echo "$LPID" > "$LFTMP" || exit 2 # Try to create hard link to file. This will work only # if lock file is not exist. while ! link "$LFTMP" "$LFILE" 2>/dev/null do sleep $LSLEEP done # Lock file is created. Unlink temp file unlink "$LFTMP" exit 0