Skip to content

Commit ee5924b

Browse files
authored
Make sure torch will only try to run as service when being started by the services.exe (#576)
1 parent bf2a87f commit ee5924b

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

‎Torch.Server/Program.cs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.IO;
44
using System.IO.Compression;
55
using System.Linq;
6+
using System.Management;
67
using System.Net;
78
using System.Reflection;
89
using System.ServiceProcess;
@@ -62,7 +63,7 @@ public static void Main(string[] args)
6263
}
6364

6465
// Breaks on Windows Server 2019
65-
if ((!new ComputerInfo().OSFullName.Contains("Server 2019") && !new ComputerInfo().OSFullName.Contains("Server 2022")) && !Environment.UserInteractive)
66+
if (IsRunningAsService())
6667
{
6768
using (var service = new TorchService(args))
6869
ServiceBase.Run(service);
@@ -81,5 +82,20 @@ public static void Main(string[] args)
8182
return;
8283
}
8384
}
85+
86+
static bool IsRunningAsService()
87+
{
88+
// Check if the parent process is services.exe
89+
using(var currentProcess = Process.GetCurrentProcess())
90+
using(var parentProcess = Process.GetProcessById(GetParentProcessId(currentProcess.Id)))
91+
return parentProcess != null && parentProcess.ProcessName.StartsWith("services", StringComparison.OrdinalIgnoreCase);
92+
}
93+
94+
static int GetParentProcessId(int processId)
95+
{
96+
using(var searcher = new ManagementObjectSearcher($"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId={processId}"))
97+
using(var results = searcher.Get())
98+
return Convert.ToInt32(results.OfType<ManagementObject>().First()["ParentProcessId"]);
99+
}
84100
}
85101
}

‎Torch.Server/Torch.Server.csproj‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@
148148
<Reference Include="System.Drawing" />
149149
<Reference Include="System.IO.Compression" />
150150
<Reference Include="System.IO.Compression.FileSystem" />
151+
<Reference Include="System.Management" />
151152
<Reference Include="System.Runtime.Serialization" />
152153
<Reference Include="System.Security.AccessControl, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
153154
<HintPath>..\packages\System.Security.AccessControl.4.4.0\lib\net461\System.Security.AccessControl.dll</HintPath>
@@ -548,4 +549,4 @@
548549
<PropertyGroup>
549550
<PostBuildEvent>copy "$(SolutionDir)NLog.config" "$(TargetDir)" &amp; copy "$(SolutionDir)NLog-user.config" "$(TargetDir)"</PostBuildEvent>
550551
</PropertyGroup>
551-
</Project>
552+
</Project>

0 commit comments

Comments
 (0)