From 92c4a81507cde60422345dec02c2a86f69cea1b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandros=20Koz=C3=A1k?= Date: Thu, 13 Dec 2018 14:24:11 -0800 Subject: [PATCH] @mafredri's flock solution https://github.com/rupa/z/pull/199 --- zsh-z.plugin.zsh | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/zsh-z.plugin.zsh b/zsh-z.plugin.zsh index 43fd1cc..0b71e03 100644 --- a/zsh-z.plugin.zsh +++ b/zsh-z.plugin.zsh @@ -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"