Public
Snippet #10 · created by Georg GH. Hopp ·

script_lock

script_lock.sh
#!/bin/sh

function lock() {
	local PIDFILE PID;

	test $# -ne 1 && {
		echo "lock(): usage: lock PIDFILE" >&2
		exit 1
	}

	PIDFILE=$1

	# If LOCK_WAIT is set we first try to aquire the lock on $PIDFILE
	test ${LOCK_WAIT:-0} -eq 1 && {
		if [ "${LOCK_WAIT_TIMEOUT}" ]
		then
			exec env LOCK_WAIT=0 flock -w "${LOCK_WAIT_TIMEOUT}" \
				-e "${PIDFILE}" "$0" "${ARGS}"
		else
			exec env LOCK_WAIT=0 flock -e "${PIDFILE}" "$0" "${ARGS}"
		fi
	}

	test -f "${PIDFILE}" && {
		PID=$(cat "${PIDFILE}")
		kill -s 0 ${PID} 2>/dev/null && {
			echo "lock(): ${PIDFILE} already used by ${PID}" >&2
			exit 1
		}
	}

	echo $$ >"${PIDFILE}" || {
		echo "lock(): unable to aquire ${PIDFILE}" >&2
		exit 1
	}
}

# ensure that /var/run/lock-test/ is writeable for the current user
lock /var/run/lock-test/lock-test.pid
echo "foo"
sleep 30
echo "bar"

# vim: set ts=4 sw=4:
Please register or login to post a comment