48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
//go:build !windows
|
||
// +build !windows
|
||
|
||
package cmd
|
||
|
||
import (
|
||
"os"
|
||
"os/user"
|
||
)
|
||
|
||
// tryRunAsSystemService 尝试作为系统服务运行 (非 Windows)
|
||
func tryRunAsSystemService() (bool, error) {
|
||
// 检查是否由系统服务管理器启动
|
||
// 如果是,返回 false 让主服务逻辑继续运行
|
||
// 这里只是用来检测运行环境,不影响服务的实际启动
|
||
|
||
// 在 Linux 下,无论是否由 systemd 启动,都让主服务逻辑运行
|
||
return false, nil
|
||
}
|
||
|
||
// isRunningAsSystemService 检查是否作为系统服务运行
|
||
func isRunningAsSystemService() bool {
|
||
// 检查常见的系统服务环境变量
|
||
serviceIndicators := []string{
|
||
"INVOCATION_ID", // systemd
|
||
"JOURNAL_STREAM", // systemd journal
|
||
"NOTIFY_SOCKET", // systemd notify
|
||
"MANAGERPID", // systemd
|
||
"LISTEN_PID", // systemd socket activation
|
||
}
|
||
|
||
for _, indicator := range serviceIndicators {
|
||
if os.Getenv(indicator) != "" {
|
||
return true
|
||
}
|
||
}
|
||
|
||
// 检查当前用户和进程特征
|
||
if currentUser, err := user.Current(); err == nil {
|
||
// 如果运行用户是 root 且没有 TTY,可能是系统服务
|
||
if currentUser.Uid == "0" && os.Getenv("SSH_TTY") == "" && os.Getenv("TERM") == "" {
|
||
return true
|
||
}
|
||
}
|
||
|
||
return false
|
||
}
|