diff --git a/Torch.Server/Program.cs b/Torch.Server/Program.cs index 411caaa4..b0c15526 100644 --- a/Torch.Server/Program.cs +++ b/Torch.Server/Program.cs @@ -3,6 +3,7 @@ using System.IO; using System.IO.Compression; using System.Linq; +using System.Management; using System.Net; using System.Reflection; using System.ServiceProcess; @@ -62,7 +63,7 @@ public static void Main(string[] args) } // Breaks on Windows Server 2019 - if ((!new ComputerInfo().OSFullName.Contains("Server 2019") && !new ComputerInfo().OSFullName.Contains("Server 2022")) && !Environment.UserInteractive) + if (IsRunningAsService()) { using (var service = new TorchService(args)) ServiceBase.Run(service); @@ -81,5 +82,20 @@ public static void Main(string[] args) return; } } + + static bool IsRunningAsService() + { + // Check if the parent process is services.exe + using(var currentProcess = Process.GetCurrentProcess()) + using(var parentProcess = Process.GetProcessById(GetParentProcessId(currentProcess.Id))) + return parentProcess != null && parentProcess.ProcessName.StartsWith("services", StringComparison.OrdinalIgnoreCase); + } + + static int GetParentProcessId(int processId) + { + using(var searcher = new ManagementObjectSearcher($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId={processId}")) + using(var results = searcher.Get()) + return Convert.ToInt32(results.OfType().First()["ParentProcessId"]); + } } } diff --git a/Torch.Server/Torch.Server.csproj b/Torch.Server/Torch.Server.csproj index 30f0e82d..0ec2aa57 100644 --- a/Torch.Server/Torch.Server.csproj +++ b/Torch.Server/Torch.Server.csproj @@ -148,6 +148,7 @@ + ..\packages\System.Security.AccessControl.4.4.0\lib\net461\System.Security.AccessControl.dll @@ -538,4 +539,4 @@ copy "$(SolutionDir)NLog.config" "$(TargetDir)" & copy "$(SolutionDir)NLog-user.config" "$(TargetDir)" - + \ No newline at end of file