script_lock.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/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: