rje
rje

Reputation: 6428

flock doesn't get released on logout/reboot

I'm using flock to try to ensure that only one instance of my script can run at a time. Most of the time this seems to work fine; but when I log out (I use i3wm) or when the PC is rebooted, the lock doesn't get released; on the next login the lock file will still exist and the script fails to start because it cannot acquire a new lock.

As you can see, I already tried trap to release the lock on process exit, but that doesn't help.

Am I using flock incorrectly or am I missing something else? I was under the impression that the lock should get released when the process ends, so that should include logout/reboot.

LOCK_FILE="${HOME}/.my_script.lock"

release_lock() {
    # This shouldn't be necessary but it seems
    # the lock doesn't release on i3 exit
    rm "${LOCK_FILE}"
}


(
    if [[ -n $LOGFILE ]]; then
        exec >>"$LOGFILE" 2>&1
    fi

    flock -xn 200 || { show_message "$(basename ${0}): cannot acquire lock ${LOCK_FILE}"; exit 3; }
    trap release_lock EXIT

    # Call the main function (not included in this snippet)
    main 200>&-
) 200>"${LOCK_FILE}"

Upvotes: 1

Views: 1042

Answers (1)

chepner
chepner

Reputation: 531808

Don't remove the file; just let the process holding the file open exit.

(
    if [[ -n $LOGFILE ]]; then
        exec >>"$LOGFILE" 2>&1
    fi

    flock -xn 200 || { show_message "$(basename ${0}): cannot acquire lock ${LOCK_FILE}"; exit 3; }

    main
) 200>"${LOCK_FILE}"

When main exists, the subshell that opened $LOCK_FILE will exit as well, and the lock will be dropped.

If you want to release the lock explicitly, use flock --unlock 200 instead of removing the file.

Upvotes: 2

Related Questions