From a791677c975928e54952daa57247354232dae2d4 Mon Sep 17 00:00:00 2001 From: Ingo Meyer Date: Thu, 18 Nov 2021 09:21:30 +0100 Subject: [PATCH] Wait for the sqlite3 process to terminate When closing the pipe to sqlite3, the sqlite3 process is not terminated instantly which leads to race conditions with Git in `histdb-sync`. Therefore, this commit adds a block to wait for the sqlite3 process to terminate in `_histdb_stop_sqlite_pipe`. --- sqlite-history.zsh | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/sqlite-history.zsh b/sqlite-history.zsh index 43fe519..499ee39 100644 --- a/sqlite-history.zsh +++ b/sqlite-history.zsh @@ -15,6 +15,7 @@ else fi typeset -g HISTDB_INODE="" +typeset -g HISTDB_SQLITE_PID="" typeset -g HISTDB_SESSION="" typeset -g HISTDB_HOST="" typeset -g HISTDB_INSTALLED_IN="${(%):-%N}" @@ -36,14 +37,13 @@ _histdb_stop_sqlite_pipe () { exec {HISTDB_FD}>&-; # https://stackoverflow.com/a/22794374/2639190 fi fi - # Sometimes, it seems like closing the fd does not terminate the - # sqlite batch process, so here is a horrible fallback. - # if [[ -n $HISTDB_SQLITE_PID ]]; then - # ps -o args= -p $HISTDB_SQLITE_PID | read -r args - # if [[ $args == "sqlite3 -batch ${HISTDB_FILE}" ]]; then - # kill -TERM $HISTDB_SQLITE_PID - # fi - # fi + # Wait for the sqlite3 process to terminate + if [[ "$1" == "block" ]] && [[ -n "${HISTDB_SQLITE_PID}" ]]; then + while ps -o pid= -p "${HISTDB_SQLITE_PID}" &>/dev/null; do + sleep 1 + done + HISTDB_SQLITE_PID="" + fi } add-zsh-hook zshexit _histdb_stop_sqlite_pipe @@ -53,6 +53,7 @@ _histdb_start_sqlite_pipe () { setopt local_options no_notify no_monitor mkfifo $PIPE sqlite3 -batch -noheader "${HISTDB_FILE}" < $PIPE >/dev/null &| + HISTDB_SQLITE_PID=$! sysopen -w -o cloexec -u HISTDB_FD -- $PIPE command rm $PIPE zstat -A HISTDB_INODE +inode ${HISTDB_FILE} @@ -222,7 +223,7 @@ histdb-sync () { git add .gitattributes git add "${HISTDB_FILE:t}" fi - _histdb_stop_sqlite_pipe # Stop in case of a merge, starting again afterwards + _histdb_stop_sqlite_pipe block # Stop in case of a merge, starting again afterwards git commit -am "history" && git pull --no-edit && git push _histdb_start_sqlite_pipe popd -q