Skip to content

Commit

Permalink
@mafredri's flock solution
Browse files Browse the repository at this point in the history
  • Loading branch information
agkozak committed Dec 13, 2018
1 parent 0719a7a commit 92c4a81
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion zsh-z.plugin.zsh
Original file line number Diff line number Diff line change
Expand Up @@ -328,11 +328,31 @@ zshz() {
esac
done

# zsystem flock-based solution by @mafredri

# A temporary file that gets copied over the datafile if all goes well
local tempfile="$datafile.$RANDOM"
local tempfile="$(mktemp "${datafile}.XXXXXXXX")"

# Make sure tht the datafile exists for locking
[[ -f $datafile ]] || touch "$datafile"
local lockfd

# Grab exclusive lock (released when function exits)
zsystem flock -f lockfd "$datafile" || return

_zshz_maintain_datafile "$*" >| "$tempfile"

local ret=$?

# Replace contents of datafile with tempfile
command cat "$tempfile" >| "$datafile"

if [[ ${ZSHZ_OWNER:-${_Z_OWNER}} ]]; then
chown ${ZSHZ_OWNER:-${_Z_OWNER}}:$(id -ng ${ZSHZ_OWNER:_${_Z_OWNER}}) "$datafile"
fi

command rm -f "$tempfile"

# Avoid clobbering the datafile in a race condition
if (( $? != 0 )) && [[ -f $datafile ]]; then
command rm -f "$tempfile"
Expand Down

0 comments on commit 92c4a81

Please sign in to comment.