Skip to content

Instantly share code, notes, and snippets.

@Hexcles
Last active December 12, 2018 05:41
Show Gist options
  • Save Hexcles/3600548 to your computer and use it in GitHub Desktop.
Save Hexcles/3600548 to your computer and use it in GitHub Desktop.
Sunpinyin Speedup
#!/bin/bash
#sunpinyin_speedup.sh
# Sunpinyin Speedup Script (by memory caching using shm, and no data loss)
# You can run this script in background on GNOME logging in.
# Hexcles Ma(http://robotshell.org/), Published in Public Domain
# Capture the exit signal, make sure it is the FIRST uncommented line.
trap "do_exit" SIGHUP SIGINT SIGQUIT SIGTERM
# Backup checking interval(seconds)
CHECK_INTERVAL=900
# Force backup will be done every FORCE_BACKUP_COUNT intervals
FORCE_BACKUP_COUNT=4
SUN_DIR="${HOME}/.sunpinyin"
SHM_USERDICT="/dev/shm/sunpinyin_userdict.${USER}"
p_count=0
# Backup the userdict and restore all changes made by this script on exit.
do_exit() {
if [ $p_count -gt 0 ]
then
echo "[sunpinyin_speedup]exit, backing up"
cp -pf "${SHM_USERDICT}" "${SUN_DIR}/userdict.real"
fi
mv -f "${SUN_DIR}/userdict.real" "${SUN_DIR}/userdict"
rm -f "${SHM_USERDICT}"
echo "[sunpinyin_speedup]backup complete, now size: `ls -l ${SUN_DIR}/userdict | awk '{print $5}'`"
exit 0
}
# Work around for abnormal quit.
if [ -e "${SUN_DIR}/userdict.real" ]
then
rm -f "${SHM_USERDICT}"
mv -f "${SUN_DIR}/userdict.real" "${SUN_DIR}/userdict"
fi
# Rename the real userdict, copy it to RAM and make a symblic link back.
# From now on the modification and query on userdict takes place in RAM.
mv -f "${SUN_DIR}/userdict" "${SUN_DIR}/userdict.real"
cp -pf "${SUN_DIR}/userdict.real" "${SHM_USERDICT}"
ln -sf "${SHM_USERDICT}" "${SUN_DIR}/userdict"
# Automatically backup the userdict, make sure not losing the modification.
while :
do
p_count=$(($p_count+1))
for (( i=0; i<CHECK_INTERVAL; i++ ))
do
sleep 1
done
if [ $p_count == $FORCE_BACKUP_COUNT ]
then
cp -pf "${SHM_USERDICT}" "${SUN_DIR}/userdict.real"
p_count=0
fi
p_mtime_shm=$(stat -c %Y "${SHM_USERDICT}")
p_mtime_real=$(stat -c %Y "${SUN_DIR}/userdict.real")
if [ $p_mtime_shm -gt $p_mtime_real ]
then
echo "[sunpinyin_speedup] `date +%T` userdict modified, backup"
echo "shm: ${p_mtime_shm} real: ${p_mtime_real}"
cp -pf "${SHM_USERDICT}" "${SUN_DIR}/userdict.real"
echo "[sunpinyin_speedup] `date +%T` done, now size: `ls -l ${SUN_DIR}/userdict.real | awk '{print $5}'`"
p_count=0
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment