64 lines
2.6 KiB
C#
64 lines
2.6 KiB
C#
using System.Diagnostics;
|
|
|
|
namespace Ads.Desktop;
|
|
|
|
public sealed record ProcessResult(int ExitCode, string Output, string Error);
|
|
|
|
public static class ProcessTools
|
|
{
|
|
public static ProcessStartInfo CreateStartInfo(string executable, IEnumerable<string> arguments)
|
|
{
|
|
var info = new ProcessStartInfo(executable)
|
|
{
|
|
UseShellExecute = false, CreateNoWindow = true,
|
|
RedirectStandardOutput = true, RedirectStandardError = true
|
|
};
|
|
foreach (var argument in arguments) info.ArgumentList.Add(argument);
|
|
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_ADMIN_TOKEN", "ADS_CONNECT_ADDRESS" })
|
|
info.Environment.Remove(key);
|
|
info.Environment["NO_COLOR"] = "1";
|
|
return info;
|
|
}
|
|
|
|
public static ProcessStartInfo ClientStartInfo(string executable, string adb, RelayOptions relay, string device, string endpoint)
|
|
{
|
|
var arguments = new List<string> { "--server", relay.BaseUri.ToString().TrimEnd('/'), "--device", device, "--listen", endpoint, "--adb", adb };
|
|
if (relay.Origin.Length > 0) arguments.AddRange(["--connect-address", relay.Origin]);
|
|
var info = CreateStartInfo(executable, arguments);
|
|
info.Environment["ADS_CLIENT_TOKEN"] = relay.Token;
|
|
return info;
|
|
}
|
|
|
|
public static async Task<ProcessResult> RunAsync(ProcessStartInfo info, CancellationToken cancellation = default)
|
|
{
|
|
using var process = Process.Start(info) ?? throw new InvalidOperationException("程序无法启动。");
|
|
var output = process.StandardOutput.ReadToEndAsync();
|
|
var error = process.StandardError.ReadToEndAsync();
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
try { await process.WaitForExitAsync(timeout.Token); }
|
|
catch
|
|
{
|
|
if (!process.HasExited) process.Kill(entireProcessTree: true);
|
|
throw;
|
|
}
|
|
return new ProcessResult(process.ExitCode, await output, await error);
|
|
}
|
|
|
|
public static async Task StopAsync(Process? process)
|
|
{
|
|
if (process == null) return;
|
|
try
|
|
{
|
|
if (!process.HasExited)
|
|
{
|
|
process.Kill(entireProcessTree: true);
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
await process.WaitForExitAsync(timeout.Token);
|
|
}
|
|
}
|
|
catch (InvalidOperationException) when (process.HasExited) { }
|
|
finally { process.Dispose(); }
|
|
}
|
|
}
|