mirror of
https://gitee.com/wanwujie/sub2api
synced 2026-04-04 15:32:13 +08:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0e89992f7 | ||
|
|
4eaa0cf14a |
@@ -3,12 +3,39 @@ package sysutil
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
const serviceName = "sub2api"
|
||||
|
||||
// findExecutable finds the full path of an executable
|
||||
// by checking common system paths
|
||||
func findExecutable(name string) string {
|
||||
// First try exec.LookPath (uses current PATH)
|
||||
if path, err := exec.LookPath(name); err == nil {
|
||||
return path
|
||||
}
|
||||
|
||||
// Fallback: check common paths
|
||||
commonPaths := []string{
|
||||
"/usr/bin/" + name,
|
||||
"/bin/" + name,
|
||||
"/usr/sbin/" + name,
|
||||
"/sbin/" + name,
|
||||
}
|
||||
|
||||
for _, path := range commonPaths {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
// Return the name as-is and let exec fail with a clear error
|
||||
return name
|
||||
}
|
||||
|
||||
// RestartService triggers a service restart via systemd.
|
||||
//
|
||||
// IMPORTANT: This function initiates the restart and returns immediately.
|
||||
@@ -30,10 +57,27 @@ func RestartService() error {
|
||||
|
||||
log.Println("Initiating service restart...")
|
||||
|
||||
// Find full paths for sudo and systemctl
|
||||
// This ensures the commands work even if PATH is limited in systemd service
|
||||
sudoPath := findExecutable("sudo")
|
||||
systemctlPath := findExecutable("systemctl")
|
||||
|
||||
log.Printf("Using sudo: %s, systemctl: %s", sudoPath, systemctlPath)
|
||||
|
||||
// The sub2api user has NOPASSWD sudo access for systemctl commands
|
||||
// (configured by install.sh in /etc/sudoers.d/sub2api).
|
||||
// Use -n (non-interactive) to prevent sudo from waiting for password input
|
||||
cmd := exec.Command("sudo", "-n", "systemctl", "restart", serviceName)
|
||||
//
|
||||
// Use setsid to create a new session, ensuring the child process
|
||||
// survives even if the parent process is killed by systemctl restart
|
||||
setsidPath := findExecutable("setsid")
|
||||
cmd := exec.Command(setsidPath, sudoPath, "-n", systemctlPath, "restart", serviceName)
|
||||
|
||||
// Detach from parent's stdio to ensure clean separation
|
||||
cmd.Stdin = nil
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("failed to initiate service restart: %w", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user