开发者

KSH: Block two process from running at the same time

开发者 https://www.devze.com 2023-04-05 09:54 出处:网络
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

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 proc开发者_如何学编程ess 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号