| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Runtime.InteropServices; |
| | | 3 | | using System.Text; |
| | | 4 | | |
| | | 5 | | namespace ToolCore; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Исполнитель внешних процессов (git, dotnet, sh), адаптированный для .NET Standard 2.0. |
| | | 9 | | /// Обеспечивает жесткие таймауты, ограничение памяти и убийство всего дерева процессов. |
| | | 10 | | /// </summary> |
| | 38 | 11 | | public class ProcessExecutor(ILogger logger) |
| | | 12 | | { |
| | 38 | 13 | | private readonly ILogger _logger = logger ?? new NullLogger(); |
| | | 14 | | |
| | 2 | 15 | | public ProcessExecutor() : this(new NullLogger()) |
| | | 16 | | { |
| | 2 | 17 | | } |
| | | 18 | | |
| | | 19 | | public const int DefaultOutputLimit = 30_000; // ~30 KB |
| | | 20 | | public const int MaxOutputLines = 50_000; |
| | | 21 | | |
| | 2 | 22 | | private static readonly Dictionary<string, string> NonInteractiveEnv = new() |
| | 2 | 23 | | { |
| | 2 | 24 | | ["TERM"] = "dumb", // тупая консоль - никакого интерактива |
| | 2 | 25 | | ["NO_COLOR"] = "1", // отключает ANSI-цвета |
| | 2 | 26 | | ["GIT_PAGER"] = "cat", // git без пейджера |
| | 2 | 27 | | ["GIT_CONFIG_PARAMETERS"] = "'color.ui=false'", |
| | 2 | 28 | | ["GIT_TERMINAL_PROMPT"] = "0", // запрещает Git запрашивать пароль |
| | 2 | 29 | | ["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1", // убирает телеметрию dotnet |
| | 2 | 30 | | ["DOTNET_CLI_UI_LANGUAGE"] = "en-US", // английский вывод dotnet |
| | 2 | 31 | | ["DOTNET_NOLOGO"] = "true", // убирает приветствие dotnet |
| | 2 | 32 | | ["DOTNET_TERMINAL_LOGGER"] = "0", // отключает terminal logger (перерисовку строк) |
| | 2 | 33 | | ["LANG"] = "en_US.UTF-8", // UTF-8 для утилит |
| | 2 | 34 | | ["LC_ALL"] = "en_US.UTF-8", |
| | 2 | 35 | | }; |
| | | 36 | | |
| | | 37 | | public static void ConfigureNonInteractiveEnvironment(ProcessStartInfo startInfo) |
| | | 38 | | { |
| | 720 | 39 | | foreach (var kvp in NonInteractiveEnv) |
| | | 40 | | { |
| | 330 | 41 | | startInfo.EnvironmentVariables[kvp.Key] = kvp.Value; |
| | | 42 | | } |
| | 30 | 43 | | } |
| | | 44 | | |
| | | 45 | | public static string? FindGitSh() |
| | | 46 | | { |
| | 20 | 47 | | if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 48 | | { |
| | | 49 | | // На Linux/macOS sh обычно в /bin/sh или /usr/bin/sh |
| | 20 | 50 | | var shPath = GetFullPathCommand("sh"); |
| | 40 | 51 | | if (shPath != null) return shPath; |
| | | 52 | | } |
| | | 53 | | |
| | 0 | 54 | | if (GetFullPathCommand("sh.exe") != null) |
| | 0 | 55 | | return "sh.exe"; |
| | | 56 | | |
| | 0 | 57 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 58 | | { |
| | 0 | 59 | | string[] registryPaths = [ |
| | 0 | 60 | | @"SOFTWARE\GitForWindows", |
| | 0 | 61 | | @"SOFTWARE\WOW6432Node\GitForWindows" |
| | 0 | 62 | | ]; |
| | | 63 | | |
| | 0 | 64 | | foreach (var path in registryPaths) |
| | | 65 | | { |
| | | 66 | | try |
| | | 67 | | { |
| | 0 | 68 | | using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(path); |
| | 0 | 69 | | if (key?.GetValue("InstallPath") is string installPath && !string.IsNullOrEmpty(installPath)) |
| | | 70 | | { |
| | 0 | 71 | | var shPath = Path.Combine(installPath, "bin", "sh.exe"); |
| | 0 | 72 | | if (File.Exists(shPath)) |
| | 0 | 73 | | return shPath; |
| | | 74 | | } |
| | 0 | 75 | | } |
| | 0 | 76 | | catch |
| | | 77 | | { |
| | | 78 | | // Игнорируем ошибки доступа к реестру |
| | 0 | 79 | | } |
| | | 80 | | } |
| | | 81 | | |
| | 0 | 82 | | var defaultPath = @"C:\Program Files\Git\bin\sh.exe"; |
| | 0 | 83 | | if (File.Exists(defaultPath)) return defaultPath; |
| | | 84 | | } |
| | | 85 | | |
| | 0 | 86 | | return null; |
| | 0 | 87 | | } |
| | | 88 | | |
| | | 89 | | private static string? GetFullPathCommand(string commandName) |
| | | 90 | | { |
| | 36 | 91 | | if (commandName.Contains(Path.DirectorySeparatorChar) || commandName.Contains(Path.AltDirectorySeparatorChar)) |
| | | 92 | | { |
| | 4 | 93 | | return File.Exists(commandName) ? commandName : null; |
| | | 94 | | } |
| | | 95 | | |
| | 32 | 96 | | var extensions = Environment.GetEnvironmentVariable("PATHEXT")?.Split(';') |
| | 32 | 97 | | ?? [".exe", ".com", ".bat", ".cmd"]; |
| | | 98 | | |
| | 32 | 99 | | var paths = Environment.GetEnvironmentVariable("PATH")?.Split(Path.PathSeparator) ?? []; |
| | | 100 | | |
| | | 101 | | // Безопасность: Убираем текущую папку из приоритета поиска, сначала ищем в системе |
| | 32 | 102 | | var searchPaths = paths.Concat([Directory.GetCurrentDirectory()]); |
| | | 103 | | |
| | 32 | 104 | | var fileNameExt = Path.GetExtension(commandName).ToUpperInvariant(); |
| | 32 | 105 | | var hasExecutableExtension = !string.IsNullOrEmpty(fileNameExt) && extensions.Contains(fileNameExt); |
| | | 106 | | |
| | 826 | 107 | | foreach (var directory in searchPaths) |
| | | 108 | | { |
| | 396 | 109 | | if (string.IsNullOrEmpty(directory)) continue; |
| | 396 | 110 | | var fullPathWithOriginalName = Path.Combine(directory, commandName); |
| | | 111 | | |
| | 396 | 112 | | if (hasExecutableExtension && File.Exists(fullPathWithOriginalName)) |
| | | 113 | | { |
| | 0 | 114 | | return fullPathWithOriginalName; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | // На non-Windows исполняемые файлы не имеют расширения (.exe и т.д.) |
| | 396 | 118 | | if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && File.Exists(fullPathWithOriginalName)) |
| | | 119 | | { |
| | 30 | 120 | | return fullPathWithOriginalName; |
| | | 121 | | } |
| | | 122 | | |
| | 3660 | 123 | | foreach (var ext in extensions) |
| | | 124 | | { |
| | 1464 | 125 | | var candidatePath = Path.ChangeExtension(fullPathWithOriginalName, ext); |
| | 1464 | 126 | | if (File.Exists(candidatePath)) |
| | | 127 | | { |
| | 0 | 128 | | return candidatePath; |
| | | 129 | | } |
| | | 130 | | } |
| | | 131 | | } |
| | | 132 | | |
| | 2 | 133 | | return null; |
| | 30 | 134 | | } |
| | | 135 | | |
| | | 136 | | /// <summary> |
| | | 137 | | /// Прямой запуск исполняемого файла с передачей аргументов |
| | | 138 | | /// </summary> |
| | | 139 | | public async Task<ProcessResult> ExecuteAsync( |
| | | 140 | | string command, |
| | | 141 | | string arguments, |
| | | 142 | | string? workingDirectory = null, |
| | | 143 | | int timeoutMs = 30000, |
| | | 144 | | int outputLimit = DefaultOutputLimit, |
| | | 145 | | CancellationToken cancellationToken = default) |
| | | 146 | | { |
| | | 147 | | // Отмена, запрошенная ДО старта, должна уважаться: процесс не запускаем вообще. |
| | | 148 | | // Иначе исход зависит от гонки «успел ли процесс завершиться раньше, чем мы проверим |
| | | 149 | | // токен» — на Linux `echo` выходит за пару миллисекунд и результат становится Success. |
| | 36 | 150 | | var preCancelled = TryGetPreCancelledResult(cancellationToken); |
| | 36 | 151 | | if (preCancelled != null) |
| | 4 | 152 | | return preCancelled; |
| | | 153 | | |
| | | 154 | | try |
| | | 155 | | { |
| | 32 | 156 | | _logger.Log($"Executing command: {command} (arguments redacted)"); |
| | | 157 | | |
| | | 158 | | string? fullCommand; |
| | 32 | 159 | | if (command == "sh") |
| | | 160 | | { |
| | 16 | 161 | | fullCommand = FindGitSh(); |
| | 16 | 162 | | if (fullCommand == null) |
| | | 163 | | { |
| | 0 | 164 | | return new ProcessResult { Success = false, Error = "Git sh not found. Bash execution is unavailable |
| | | 165 | | } |
| | | 166 | | } |
| | | 167 | | else |
| | | 168 | | { |
| | 16 | 169 | | fullCommand = GetFullPathCommand(command); |
| | 16 | 170 | | if (fullCommand == null) |
| | | 171 | | { |
| | 2 | 172 | | return new ProcessResult { Success = false, Error = $"Failed to find executable: {command} in system |
| | | 173 | | } |
| | | 174 | | } |
| | | 175 | | |
| | 30 | 176 | | var startInfo = new ProcessStartInfo |
| | 30 | 177 | | { |
| | 30 | 178 | | FileName = fullCommand, |
| | 30 | 179 | | Arguments = arguments, |
| | 30 | 180 | | RedirectStandardInput = false, |
| | 30 | 181 | | RedirectStandardOutput = true, |
| | 30 | 182 | | RedirectStandardError = true, |
| | 30 | 183 | | StandardOutputEncoding = Encoding.UTF8, |
| | 30 | 184 | | StandardErrorEncoding = Encoding.UTF8, |
| | 30 | 185 | | UseShellExecute = false, |
| | 30 | 186 | | CreateNoWindow = true, |
| | 30 | 187 | | WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory |
| | 30 | 188 | | }; |
| | | 189 | | |
| | 30 | 190 | | ConfigureNonInteractiveEnvironment(startInfo); |
| | | 191 | | |
| | 30 | 192 | | return await RunProcessInternalAsync(startInfo, timeoutMs, outputLimit, cancellationToken); |
| | | 193 | | } |
| | 0 | 194 | | catch (Exception ex) |
| | | 195 | | { |
| | 0 | 196 | | _logger.Log($"Process initialization error: {ex.Message}", "ERROR"); |
| | 0 | 197 | | return new ProcessResult { Success = false, Error = $"Initialization failed: {ex.Message}" }; |
| | | 198 | | } |
| | 36 | 199 | | } |
| | | 200 | | |
| | | 201 | | /// <summary> |
| | | 202 | | /// Запуск bash-скрипта/команды через временный файл. |
| | | 203 | | /// Надёжнее, чем '-c': нет проблем с экранированием кавычек и лимитом длины командной строки. |
| | | 204 | | /// </summary> |
| | | 205 | | public async Task<ProcessResult> ExecuteBashAsync( |
| | | 206 | | string bashScript, |
| | | 207 | | string? workingDirectory = null, |
| | | 208 | | int timeoutMs = 120_000, |
| | | 209 | | int outputLimit = DefaultOutputLimit, |
| | | 210 | | CancellationToken cancellationToken = default) |
| | | 211 | | { |
| | | 212 | | // Как и ExecuteAsync: не создаём временный файл и не спавним sh, если отмена уже запрошена. |
| | | 213 | | // Без этой проверки Task.Delay ниже бросил бы OperationCanceledException вместо |
| | | 214 | | // возврата результата с флагом Cancelled. |
| | 6 | 215 | | var preCancelled = TryGetPreCancelledResult(cancellationToken); |
| | 6 | 216 | | if (preCancelled != null) |
| | 2 | 217 | | return preCancelled; |
| | | 218 | | |
| | 4 | 219 | | var shPath = FindGitSh(); |
| | 4 | 220 | | if (shPath == null) |
| | | 221 | | { |
| | 0 | 222 | | return new ProcessResult { Success = false, Error = "Git sh not found. Cannot execute bash commands." }; |
| | | 223 | | } |
| | | 224 | | |
| | | 225 | | // Временный файл со скриптом — снимает проблемы экранирования и длины командной строки. |
| | 4 | 226 | | var tempScript = Path.Combine(Path.GetTempPath(), $"invait_{Guid.NewGuid():N}.sh"); |
| | | 227 | | try |
| | | 228 | | { |
| | | 229 | | // netstandard2.0 не имеет File.WriteAllTextAsync — используем синхронную запись. |
| | 4 | 230 | | File.WriteAllText(tempScript, bashScript, new UTF8Encoding(false)); |
| | | 231 | | |
| | 4 | 232 | | await Task.Delay(100, cancellationToken); // чуть ожидаем, а то файл не всегда создается |
| | 4 | 233 | | if (!File.Exists(tempScript)) |
| | 0 | 234 | | return new ProcessResult { Success = false, Error = "Failed to create TMP sh file" }; |
| | | 235 | | |
| | | 236 | | // sh <файл> — скрипт передаётся через stdin файла, а не через аргументы. |
| | 4 | 237 | | var arguments = $"\"{tempScript}\""; |
| | 4 | 238 | | return await ExecuteAsync(shPath, arguments, workingDirectory, timeoutMs, outputLimit, cancellationToken); |
| | | 239 | | } |
| | | 240 | | finally |
| | | 241 | | { |
| | 8 | 242 | | try { File.Delete(tempScript); } catch { /* Игнорируем ошибку удаления временного файла */ } |
| | | 243 | | } |
| | 6 | 244 | | } |
| | | 245 | | private async Task<ProcessResult> RunProcessInternalAsync( |
| | | 246 | | ProcessStartInfo startInfo, |
| | | 247 | | int timeoutMs, |
| | | 248 | | int outputLimit, |
| | | 249 | | CancellationToken cancellationToken) |
| | | 250 | | { |
| | 30 | 251 | | using var process = new Process { StartInfo = startInfo }; |
| | | 252 | | |
| | 30 | 253 | | if (!process.Start()) |
| | | 254 | | { |
| | 0 | 255 | | return new ProcessResult { Success = false, Error = "Failed to start process." }; |
| | | 256 | | } |
| | | 257 | | |
| | 30 | 258 | | var processId = process.Id; |
| | 30 | 259 | | var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
| | 30 | 260 | | process.EnableRaisingEvents = true; |
| | 30 | 261 | | process.Exited += (s, e) => tcs.TrySetResult(true); |
| | | 262 | | |
| | 30 | 263 | | if (process.HasExited) |
| | | 264 | | { |
| | 2 | 265 | | tcs.TrySetResult(true); |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | // Читаем потоки асинхронно, поблочно и с лимитом |
| | 30 | 269 | | var stdoutTask = ReadStreamLimitedAsync(process.StandardOutput, outputLimit, cancellationToken); |
| | 30 | 270 | | var stderrTask = ReadStreamLimitedAsync(process.StandardError, outputLimit, cancellationToken); |
| | | 271 | | |
| | | 272 | | // Три независимых сигнала: выход процесса, таймаут, отмена. |
| | | 273 | | // Таймаут НЕ связываем с токеном отмены, чтобы не путать отмену с таймаутом. |
| | 30 | 274 | | var exitTask = tcs.Task; |
| | 30 | 275 | | var timeoutTask = Task.Delay(timeoutMs, CancellationToken.None); |
| | 30 | 276 | | var cancelTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
| | 30 | 277 | | using var cancelReg = cancellationToken.Register(() => cancelTcs.TrySetResult(true)); |
| | 30 | 278 | | if (cancellationToken.IsCancellationRequested) cancelTcs.TrySetResult(true); |
| | 30 | 279 | | var cancelTask = cancelTcs.Task; |
| | | 280 | | |
| | 30 | 281 | | var completed = await Task.WhenAny(exitTask, timeoutTask, cancelTask); |
| | | 282 | | |
| | 30 | 283 | | var timedOut = completed == timeoutTask; |
| | 30 | 284 | | var cancelled = completed == cancelTask; |
| | 30 | 285 | | var wasKilled = false; |
| | | 286 | | |
| | 30 | 287 | | if (timedOut || cancelled) |
| | | 288 | | { |
| | 10 | 289 | | wasKilled = true; |
| | 10 | 290 | | KillProcessTree(processId); // Жестко убиваем всё дерево процессов |
| | | 291 | | |
| | 10 | 292 | | await Task.WhenAny(exitTask, Task.Delay(1000, CancellationToken.None)); |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | // Защищаем чтение стримов от вечного зависания зомби-процессов |
| | 30 | 296 | | var streamsTimeout = Task.Delay(2000, CancellationToken.None); |
| | 30 | 297 | | var readAllStreamsTask = Task.WhenAll(stdoutTask, stderrTask); |
| | | 298 | | |
| | 30 | 299 | | if (await Task.WhenAny(readAllStreamsTask, streamsTimeout) == streamsTimeout) |
| | | 300 | | { |
| | 0 | 301 | | _logger.Log($"Process streams reading timed out for PID {processId}.", "WARNING"); |
| | | 302 | | } |
| | | 303 | | |
| | 30 | 304 | | var stdout = stdoutTask.Status == TaskStatus.RanToCompletion |
| | 30 | 305 | | ? await stdoutTask : "[Stream reading timed out]"; |
| | 30 | 306 | | var stderr = stderrTask.Status == TaskStatus.RanToCompletion |
| | 30 | 307 | | ? await stderrTask : "[Stream reading timed out]"; |
| | | 308 | | |
| | 30 | 309 | | var exitCode = -1; |
| | 60 | 310 | | try { exitCode = process.ExitCode; } catch { } |
| | | 311 | | |
| | 30 | 312 | | var suffix = wasKilled |
| | 30 | 313 | | ? (cancelled ? "\nProcess was cancelled by the caller." : $"\nCommand timed out after {timeoutMs}ms.") |
| | 30 | 314 | | : string.Empty; |
| | | 315 | | |
| | 30 | 316 | | var result = new ProcessResult |
| | 30 | 317 | | { |
| | 30 | 318 | | Success = exitCode == 0 && !wasKilled, |
| | 30 | 319 | | Output = stdout, |
| | 30 | 320 | | Error = string.Join("\n", stderr, suffix).Trim('\n'), |
| | 30 | 321 | | ExitCode = exitCode, |
| | 30 | 322 | | TimedOut = timedOut, |
| | 30 | 323 | | Cancelled = cancelled, |
| | 30 | 324 | | WasKilled = wasKilled |
| | 30 | 325 | | }; |
| | | 326 | | |
| | 30 | 327 | | if (!result.Success && !wasKilled && !string.IsNullOrEmpty(stdout)) |
| | | 328 | | { |
| | 0 | 329 | | result.Error = string.Join("\n", stdout, stderr).Trim(); |
| | | 330 | | } |
| | | 331 | | |
| | 30 | 332 | | return result; |
| | 30 | 333 | | } |
| | | 334 | | |
| | | 335 | | /// <summary> |
| | | 336 | | /// Потоковое поблочное чтение с лимитом для защиты памяти Visual Studio |
| | | 337 | | /// </summary> |
| | | 338 | | private static async Task<string> ReadStreamLimitedAsync(StreamReader reader, int outputLimit, CancellationToken can |
| | | 339 | | { |
| | 60 | 340 | | var sb = new StringBuilder(); |
| | 60 | 341 | | var buffer = new char[4096]; |
| | 60 | 342 | | var totalCharsRead = 0; |
| | 60 | 343 | | var linesCount = 0; |
| | | 344 | | int read; |
| | | 345 | | |
| | 1037 | 346 | | while ((read = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) |
| | | 347 | | { |
| | 977 | 348 | | if (cancellationToken.IsCancellationRequested) break; |
| | | 349 | | |
| | 50242 | 350 | | for (var i = 0; i < read; i++) |
| | | 351 | | { |
| | 36160 | 352 | | if (buffer[i] == '\n') linesCount++; |
| | | 353 | | } |
| | | 354 | | |
| | 977 | 355 | | if (totalCharsRead + read > outputLimit || linesCount > MaxOutputLines) |
| | | 356 | | { |
| | 0 | 357 | | var allowed = Math.Min(read, outputLimit - totalCharsRead); |
| | 0 | 358 | | if (allowed > 0) |
| | | 359 | | { |
| | 0 | 360 | | sb.Append(buffer, 0, allowed); |
| | | 361 | | } |
| | | 362 | | |
| | 0 | 363 | | var truncatedMarker = $"\n[... Output truncated due to size/line limit ...]\n"; |
| | 0 | 364 | | sb.Insert(0, truncatedMarker); |
| | 0 | 365 | | break; |
| | | 366 | | } |
| | | 367 | | |
| | 977 | 368 | | sb.Append(buffer, 0, read); |
| | 977 | 369 | | totalCharsRead += read; |
| | | 370 | | } |
| | | 371 | | |
| | 60 | 372 | | return sb.ToString(); |
| | 60 | 373 | | } |
| | | 374 | | |
| | | 375 | | /// <summary> |
| | | 376 | | /// Возвращает результат «отменено до запуска», если токен уже отменён, иначе null. |
| | | 377 | | /// Процесс при этом не создаётся, поэтому WasKilled остаётся false. |
| | | 378 | | /// </summary> |
| | | 379 | | private static ProcessResult? TryGetPreCancelledResult(CancellationToken cancellationToken) |
| | | 380 | | { |
| | 42 | 381 | | if (!cancellationToken.IsCancellationRequested) |
| | 36 | 382 | | return null; |
| | | 383 | | |
| | 6 | 384 | | return new ProcessResult |
| | 6 | 385 | | { |
| | 6 | 386 | | Success = false, |
| | 6 | 387 | | Cancelled = true, |
| | 6 | 388 | | ExitCode = -1, |
| | 6 | 389 | | Error = "Process was not started: the operation was cancelled before launch.", |
| | 6 | 390 | | }; |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | /// <summary> |
| | | 394 | | /// Кроссплатформенное убийство всего дерева процессов для .NET Standard 2.0. |
| | | 395 | | /// </summary> |
| | | 396 | | private static void KillProcessTree(int pid) |
| | | 397 | | { |
| | 10 | 398 | | if (pid <= 0) return; |
| | | 399 | | |
| | 10 | 400 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 401 | | { |
| | 0 | 402 | | RunDetached("taskkill", $"/T /F /PID {pid}"); |
| | 0 | 403 | | return; |
| | | 404 | | } |
| | | 405 | | |
| | | 406 | | // Unix: сначала дети, потом сам процесс. Обратный порядок не работает — после смерти |
| | | 407 | | // родителя дети переподвешиваются к init, и найти их по родительскому PID уже нельзя. |
| | | 408 | | // |
| | | 409 | | // ВАЖНО: здесь нельзя использовать `kill -9 -PID` как единственную попытку. |
| | | 410 | | // Такой вызов убивает ГРУППУ процессов с PGID == PID, а дочерний процесс наследует |
| | | 411 | | // PGID тест-хоста, поэтому kill завершается с ошибкой "No such process", но НЕ бросает |
| | | 412 | | // исключение — процесс остаётся жив (тихая утечка осиротевших процессов). |
| | 10 | 413 | | RunDetached("pkill", $"-9 -P {pid}"); |
| | 10 | 414 | | RunDetached("kill", $"-9 {pid}"); |
| | 10 | 415 | | } |
| | | 416 | | |
| | | 417 | | /// <summary>Запуск внешней утилиты с жёстким ожиданием; ошибки игнорируются.</summary> |
| | | 418 | | private static void RunDetached(string fileName, string arguments) |
| | | 419 | | { |
| | | 420 | | try |
| | | 421 | | { |
| | 20 | 422 | | using var p = Process.Start(new ProcessStartInfo |
| | 20 | 423 | | { |
| | 20 | 424 | | FileName = fileName, |
| | 20 | 425 | | Arguments = arguments, |
| | 20 | 426 | | CreateNoWindow = true, |
| | 20 | 427 | | UseShellExecute = false, |
| | 20 | 428 | | }); |
| | 20 | 429 | | p?.WaitForExit(3000); |
| | 20 | 430 | | } |
| | 0 | 431 | | catch |
| | | 432 | | { |
| | | 433 | | // Утилита недоступна в этой системе — не критично: следующая попытка может сработать. |
| | 0 | 434 | | } |
| | 20 | 435 | | } |
| | | 436 | | |
| | | 437 | | private class NullLogger : ILogger |
| | | 438 | | { |
| | 2 | 439 | | public void Log(string message, string level = "INFO") { } |
| | | 440 | | } |
| | | 441 | | } |