Quick-and-dirty way to ensure only one instance of a shell script is running at a time

前端 未结 30 2471
忘掉有多难
忘掉有多难 2020-11-22 02:57

What\'s a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?

30条回答
  •  被撕碎了的回忆
    2020-11-22 03:07

    I find that bmdhack's solution is the most practical, at least for my use case. Using flock and lockfile rely on removing the lockfile using rm when the script terminates, which can't always be guaranteed (e.g., kill -9).

    I would change one minor thing about bmdhack's solution: It makes a point of removing the lock file, without stating that this is unnecessary for the safe working of this semaphore. His use of kill -0 ensures that an old lockfile for a dead process will simply be ignored/over-written.

    My simplified solution is therefore to simply add the following to the top of your singleton:

    ## Test the lock
    LOCKFILE=/tmp/singleton.lock 
    if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
        echo "Script already running. bye!"
        exit 
    fi
    
    ## Set the lock 
    echo $$ > ${LOCKFILE}
    

    Of course, this script still has the flaw that processes that are likely to start at the same time have a race hazard, as the lock test and set operations are not a single atomic action. But the proposed solution for this by lhunath to use mkdir has the flaw that a killed script may leave behind the directory, thus preventing other instances from running.

提交回复
热议问题