| | | 1 | | using System.Diagnostics; |
| | | 2 | | |
| | | 3 | | namespace Anichron.Worker.Ingestion.Proxy; |
| | | 4 | | |
| | | 5 | | internal sealed class SystemProcessLauncher : IProcessLauncher |
| | | 6 | | { |
| | | 7 | | public async Task<ProcessResult> RunAsync(string fileName, IReadOnlyList<string> arguments, CancellationToken ct) |
| | 2 | 8 | | { |
| | 2 | 9 | | using var process = new Process(); |
| | 2 | 10 | | process.StartInfo = new ProcessStartInfo |
| | 2 | 11 | | { |
| | 2 | 12 | | FileName = fileName, |
| | 2 | 13 | | RedirectStandardOutput = true, |
| | 2 | 14 | | RedirectStandardError = true, |
| | 2 | 15 | | UseShellExecute = false, |
| | 2 | 16 | | CreateNoWindow = true, |
| | 2 | 17 | | }; |
| | 14 | 18 | | foreach (var arg in arguments) |
| | 4 | 19 | | process.StartInfo.ArgumentList.Add(arg); |
| | | 20 | | |
| | 2 | 21 | | process.Start(); |
| | | 22 | | // Start draining pipes immediately — must be consumed to prevent the child process |
| | | 23 | | // from blocking on a full pipe buffer. Cancellation is signalled only via WaitForExitAsync. |
| | 2 | 24 | | await using var standardOutput = new MemoryStream(); |
| | 2 | 25 | | var stdoutTask = process.StandardOutput.BaseStream.CopyToAsync(standardOutput, CancellationToken.None); |
| | 2 | 26 | | var stderrTask = process.StandardError.ReadToEndAsync(CancellationToken.None); |
| | | 27 | | try |
| | 2 | 28 | | { |
| | 2 | 29 | | await process.WaitForExitAsync(ct); |
| | 2 | 30 | | await stdoutTask; |
| | 2 | 31 | | var standardError = await stderrTask; |
| | 2 | 32 | | return new ProcessResult(process.ExitCode, standardOutput.ToArray(), standardError); |
| | | 33 | | } |
| | 0 | 34 | | catch (OperationCanceledException) |
| | 0 | 35 | | { |
| | | 36 | | // Kill the process tree so GPU encoder children (e.g. vaenc) are not orphaned. |
| | 0 | 37 | | process.Kill(entireProcessTree: true); |
| | | 38 | | // Drain fully before returning — the killed process closes its pipes immediately. |
| | 0 | 39 | | await Task.WhenAll(stdoutTask, stderrTask); |
| | 0 | 40 | | throw; |
| | | 41 | | } |
| | 2 | 42 | | } |
| | | 43 | | } |