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

前端 未结 30 3054
忘掉有多难
忘掉有多难 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:08

    Here's an approach that combines atomic directory locking with a check for stale lock via PID and restart if stale. Also, this does not rely on any bashisms.

    #!/bin/dash
    
    SCRIPTNAME=$(basename $0)
    LOCKDIR="/var/lock/${SCRIPTNAME}"
    PIDFILE="${LOCKDIR}/pid"
    
    if ! mkdir $LOCKDIR 2>/dev/null
    then
        # lock failed, but check for stale one by checking if the PID is really existing
        PID=$(cat $PIDFILE)
        if ! kill -0 $PID 2>/dev/null
        then
           echo "Removing stale lock of nonexistent PID ${PID}" >&2
           rm -rf $LOCKDIR
           echo "Restarting myself (${SCRIPTNAME})" >&2
           exec "$0" "$@"
        fi
        echo "$SCRIPTNAME is already running, bailing out" >&2
        exit 1
    else
        # lock successfully acquired, save PID
        echo $$ > $PIDFILE
    fi
    
    trap "rm -rf ${LOCKDIR}" QUIT INT TERM EXIT
    
    
    echo hello
    
    sleep 30s
    
    echo bye
    

提交回复
热议问题