Skip to content

Instantly share code, notes, and snippets.

@rainly
Forked from gotnix/bash_lock.adoc
Created June 12, 2018 10:39
Show Gist options
  • Save rainly/53bd1cf6154546635b9b68c879bdca00 to your computer and use it in GitHub Desktop.
Save rainly/53bd1cf6154546635b9b68c879bdca00 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