Skip to content

Instantly share code, notes, and snippets.

@gotnix
Last active April 14, 2021 06:02
Show Gist options
  • Save gotnix/baddd4ab564d3db87626376716ab9501 to your computer and use it in GitHub Desktop.
Save gotnix/baddd4ab564d3db87626376716ab9501 to your computer and use it in GitHub Desktop.
利用文件锁保证一个 Shell 脚本只有一个进程在运行。

参考链接:

bash_lock.sh
#!/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 $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment