使用 flock
给 shell 脚本
上锁,保证对某些关键数据或设备的访问。
flock
lockit () {
exec 7<>.lock
flock -n 7 || {
echo "Waiting for lock to release..."
flock 7
}
}
or
#!/bin/bash
F_LOCK="/var/tmp/${0}.lock"
F_PID="/var/tmp/${0}.pid"
exec 3> ${F_LOCK}
function is_not_running () {
if ! /usr/bin/flock -xn 3
then
local pid=$(cat ${F_PID})
echo "${0} (PID: ${pid}) already running ..."
return 1
else
echo ${$} > ${F_PID}
return 0
fi
}
function clean_up () {
/usr/bin/flock -u 3
exec 4>&-
/bin/rm -f ${F_LOCK}
/bin/rm -f ${F_PID}
}
if is_not_running
then
echo "do somthing"
sleep 30
echo "done"
fi
clean_up
exit $?