Bash: Lock function

From FVue
Jump to: navigation, search


# Put lock
# @return 0 if successful, 1 if not
function prj_lock() {
    # Writing to lock file is successful?
    if set -o noclobber; echo "$$" > "$PRJ_LOCK_FILE" 2> /dev/null; then
        # Yes, writing to lock file is successful;
        result=0 
    else
        # No, writing to lock file yields errors;
        # Does lock file hold a valid pid?
        if test -n "$(cat "$PRJ_LOCK_FILE")" && ps p $(cat "$PRJ_LOCK_FILE") > /dev/null; then
            # Yes, lock file holds a valid pid;
            echo "$(logdate) Project is locked (busy)"
            result=1
        else
            # No, lock file holds a non-valid pid
            # Indicate error
            echo "Error: Project is locked by non-existing process (pid = $(cat $PRJ_LOCK_FILE))" >&2
            echo "Removing lock..." >&2
            prj_unlock
            exit 1
        fi
    fi
    return $result
} # prj_lock()


#--- prj_unlock() -------------------------------------------------------------
function prj_unlock() {
    # Remove lockfile
    rm -f $PRJ_LOCK_FILE
} # prj_unlock()

Comments

blog comments powered by Disqus