KSH:阻止两个进程同时运行
我有两个随机运行的进程,由于读写器问题,我想强制它们不要同时运行。我的想法是,每当一个进程运行时,我都会创建一个 LOCK 文件,两个进程都有一个检查 LOCK 是否存在的逻辑。如果LOCK存在,则休眠一段时间,唤醒后再次检查。这是其中的一小部分
if [[ ! -f ${INPUT_DIR}/LOCK ]]
then
#Create LOCK file
cat /dev/null > ${INPUT_DIR}/LOCK
retcode=${?}
if [[ ${retcode} -ne 0 ]]
then
echo `date` "Error in creating LOCK file by processA.sh - Error code: " ${retcode} >> ${CORE_LOG}
exit
fi
echo `date` "LOCK turns on by processA.sh" >> ${CORE_LOG}
...
rm ${INPUT_DIR}/LOCK
fi
但是,这并不能完全阻止两个进程同时运行。极少数情况下,如果日志存在,两个进程都会通过第一个 IF 检查(如果两个进程同时调用并且不存在 LOCK,则很可能会通过第一个 IF 语句) ,两者都尝试创建一个 LOCK 文件,因为 cat /dev/null >即使 LOCK 已经存在,${INPUT_DIR}/LOCK
也不会生成错误。有解决办法吗?
I have two process that running at random time and I want to force them not to ever run at the same time due to reader-writer problem. My thought is whenever a process run, I create a LOCK file, both process has a logic of checking whether a LOCK exist. If LOCK is existed, then sleep for bit and wake up and check it again. Here is a small piece of it
if [[ ! -f ${INPUT_DIR}/LOCK ]]
then
#Create LOCK file
cat /dev/null > ${INPUT_DIR}/LOCK
retcode=${?}
if [[ ${retcode} -ne 0 ]]
then
echo `date` "Error in creating LOCK file by processA.sh - Error code: " ${retcode} >> ${CORE_LOG}
exit
fi
echo `date` "LOCK turns on by processA.sh" >> ${CORE_LOG}
...
rm ${INPUT_DIR}/LOCK
fi
Howver this does not QUITE stop the two process from running at the same time. There are rare time when both process would get pass the first IF checking if the log exist (if both process get invoke at the same time and there was no LOCK exist, very likely that it will get pass the first IF statement), both try to create a LOCK file, since cat /dev/null > ${INPUT_DIR}/LOCK
will not generate an error, even when LOCK is already exist. Is there a solution to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于unix的主要版本,首选的解决方案是使用锁定目录,我认为对于linux也是如此,但我最近没有测试它。
创建目录是一个原子过程,假设您正在创建一个静态名称,如
/bin/mkdir -p /tmp/myProjWorkSpace/LOCK
,则只有 1 个过程会成功。如果您需要将信息嵌入到锁中,那么您需要一个文件,并且需要为每个进程划分子目录,可能会将 processID (.$$
) 添加到目录名称中。我希望这有帮助。
For the main versions of unix, the preferred solution is to use a lock directory, I would assume this is true for linux, but I haven't had to test it recently.
Creating a directory is an atomic process, and only 1 of the processes will succeed, assuming that you are making a static name like
/bin/mkdir -p /tmp/myProjWorkSpace/LOCK
. If you need to have information embedded in your lock, then you need a file, and you need sepqrate subdirs per process, possibly add the processID (.$$
) to the dir name.I hope this helps.