From f0e89992f70559cda2de9c4f40bc9c7188a45ba2 Mon Sep 17 00:00:00 2001 From: shaw Date: Thu, 18 Dec 2025 20:00:53 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BD=BF=E7=94=A8=20setsid=20=E7=A1=AE?= =?UTF-8?q?=E4=BF=9D=E9=87=8D=E5=90=AF=E5=91=BD=E4=BB=A4=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E4=BA=8E=E7=88=B6=E8=BF=9B=E7=A8=8B=E6=89=A7=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题原因: - cmd.Start() 启动的子进程与父进程在同一会话中 - 当 systemctl restart 发送 SIGTERM 给父进程时 - 子进程可能也会被终止,导致重启命令无法完成 修复内容: - 使用 setsid 创建新会话,子进程完全独立于父进程 - 分离标准输入/输出/错误流 - 确保即使父进程被 kill,重启命令仍能执行完成 --- backend/internal/pkg/sysutil/restart.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/backend/internal/pkg/sysutil/restart.go b/backend/internal/pkg/sysutil/restart.go index a09f5d2e..369ffc47 100644 --- a/backend/internal/pkg/sysutil/restart.go +++ b/backend/internal/pkg/sysutil/restart.go @@ -67,7 +67,17 @@ func RestartService() error { // 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(sudoPath, "-n", systemctlPath, "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) }