This commit is contained in:
Wang Sen Di
2025-11-23 14:15:20 +08:00
parent dbd83b7705
commit 6ba67a8d85
22 changed files with 519 additions and 0 deletions

39
hook/singleton.sh Normal file
View File

@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# shellcheck disable=SC2001
# 单例模式
# 示例
# # shellcheck disable=SC1091
# if [[ -d "/host/proc/1/" ]]; then source /apps/gitrce/hook/singleton.sh "$0"; fi
__singleton_pattern() {
# 实现单例模式,确保同一时刻只有一个脚本实例在运行
_script_path_this=$(realpath "$(ps -p $$ -o args= 2>/dev/null | awk '{print $2}')")
# 生成 PID 文件的路径
_pid_name="$(echo "$_script_path_this" | sed 's:^/::; s/\//#/g; s/\.sh$/.pid/')" # 还原 echo "$result" | sed 's:^:/:' | sed 's/#/\//g; s/\.pid$/.sh/'
_pid_file="/apps/pid/$_pid_name"
# 创建 PID 文件所在的目录
mkdir -p "${_pid_file%/*}"
# 从 PID 文件中读取存储的 PID
_pid_data=$(cat "$_pid_file" 2>/dev/null)
# 根据存储的 PID 获取对应脚本的绝对路径
_script_path_pid=$(realpath "$(ps -p "$_pid_data" -o args= 2>/dev/null | awk '{print $2}')" 2>/dev/null)
if [[ "$_script_path_this" != "$_script_path_pid" ]]; then
# 如果当前脚本路径与存储的脚本路径不同,则更新 PID 文件并继续执行
echo "$$" >"$_pid_file"
else
# 如果相同,则说明已有实例在运行,输出相关信息并退出
echo "脚本单例模式运行, 已存在运行实例,当前脚本已退出"
echo "_pid_file: $_pid_file"
echo "_pid_data: $_pid_data"
echo "_script_path_this: $_script_path_this"
echo "_script_path_pid : $_script_path_pid"
exit 0
fi
}
__singleton_pattern